all repos — flounder @ f434d18e0dcfbd41fe123bf9a5b853f8016929a8

A small site builder for the Gemini protocol

http.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"database/sql"
  6	"git.sr.ht/~adnano/gmi"
  7	"github.com/gorilla/handlers"
  8	"github.com/gorilla/sessions"
  9	_ "github.com/mattn/go-sqlite3"
 10	"golang.org/x/crypto/bcrypt"
 11	"html/template"
 12	"io"
 13	"io/ioutil"
 14	"log"
 15	"net/http"
 16	"os"
 17	"path"
 18	"path/filepath"
 19	"strings"
 20	"time"
 21)
 22
 23var t *template.Template
 24var DB *sql.DB
 25var SessionStore *sessions.CookieStore
 26
 27const InternalServerErrorMsg = "500: Internal Server Error"
 28
 29func renderError(w http.ResponseWriter, errorMsg string, statusCode int) {
 30	data := struct {
 31		PageTitle string
 32		ErrorMsg  string
 33	}{"Error!", errorMsg}
 34	err := t.ExecuteTemplate(w, "error.html", data)
 35	if err != nil { // shouldn't happen probably
 36		http.Error(w, errorMsg, statusCode)
 37	}
 38}
 39
 40func rootHandler(w http.ResponseWriter, r *http.Request) {
 41	// serve everything inside static directory
 42	if r.URL.Path != "/" {
 43		fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path))
 44		http.ServeFile(w, r, fileName)
 45		return
 46	}
 47	_, authd := getAuthUser(r)
 48	indexFiles, err := getIndexFiles()
 49	if err != nil {
 50		log.Println(err)
 51		renderError(w, InternalServerErrorMsg, 500)
 52		return
 53	}
 54	allUsers, err := getUsers()
 55	if err != nil {
 56		log.Println(err)
 57		renderError(w, InternalServerErrorMsg, 500)
 58		return
 59	}
 60	data := struct {
 61		Host      string
 62		PageTitle string
 63		Files     []*File
 64		Users     []string
 65		LoggedIn  bool
 66	}{c.Host, c.SiteTitle, indexFiles, allUsers, authd}
 67	err = t.ExecuteTemplate(w, "index.html", data)
 68	if err != nil {
 69		log.Println(err)
 70		renderError(w, InternalServerErrorMsg, 500)
 71		return
 72	}
 73}
 74
 75func editFileHandler(w http.ResponseWriter, r *http.Request) {
 76	session, _ := SessionStore.Get(r, "cookie-session")
 77	authUser, ok := session.Values["auth_user"].(string)
 78	if !ok {
 79		renderError(w, "Forbidden", 403)
 80		return
 81	}
 82	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
 83	filePath := path.Join(c.FilesDirectory, authUser, fileName)
 84	if r.Method == "GET" {
 85		err := checkIfValidFile(filePath, nil)
 86		if err != nil {
 87			log.Println(err)
 88			renderError(w, err.Error(), 400)
 89			return
 90		}
 91		f, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0644)
 92		defer f.Close()
 93		fileBytes, err := ioutil.ReadAll(f)
 94		if err != nil {
 95			log.Println(err)
 96			renderError(w, InternalServerErrorMsg, 500)
 97			return
 98		}
 99		data := struct {
100			FileName  string
101			FileText  string
102			PageTitle string
103		}{fileName, string(fileBytes), c.SiteTitle}
104		err = t.ExecuteTemplate(w, "edit_file.html", data)
105		if err != nil {
106			log.Println(err)
107			renderError(w, InternalServerErrorMsg, 500)
108			return
109		}
110	} else if r.Method == "POST" {
111		// get post body
112		r.ParseForm()
113		fileBytes := []byte(r.Form.Get("file_text"))
114		err := checkIfValidFile(filePath, fileBytes)
115		if err != nil {
116			log.Println(err)
117			renderError(w, err.Error(), 400)
118			return
119		}
120		err = ioutil.WriteFile(filePath, fileBytes, 0644)
121		if err != nil {
122			log.Println(err)
123			renderError(w, InternalServerErrorMsg, 500)
124			return
125		}
126		http.Redirect(w, r, "/my_site", 302)
127	}
128}
129
130func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
131	if r.Method == "POST" {
132		session, _ := SessionStore.Get(r, "cookie-session")
133		authUser, ok := session.Values["auth_user"].(string)
134		if !ok {
135			renderError(w, "Forbidden", 403)
136			return
137		}
138		r.ParseMultipartForm(10 << 6) // why does this not work
139		file, fileHeader, err := r.FormFile("file")
140		fileName := filepath.Clean(fileHeader.Filename)
141		defer file.Close()
142		if err != nil {
143			log.Println(err)
144			renderError(w, err.Error(), 400)
145			return
146		}
147		dest, _ := ioutil.ReadAll(file)
148		err = checkIfValidFile(fileName, dest)
149		if err != nil {
150			log.Println(err)
151			renderError(w, err.Error(), 400)
152			return
153		}
154		destPath := path.Join(c.FilesDirectory, authUser, fileName)
155
156		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
157		if err != nil {
158			log.Println(err)
159			renderError(w, InternalServerErrorMsg, 500)
160			return
161		}
162		defer f.Close()
163		io.Copy(f, bytes.NewReader(dest))
164	}
165	http.Redirect(w, r, "/my_site", 302)
166}
167
168// bool whether auth'd, string is auth user
169func getAuthUser(r *http.Request) (string, bool) {
170	session, _ := SessionStore.Get(r, "cookie-session")
171	user, ok := session.Values["auth_user"].(string)
172	return user, ok
173}
174func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
175	authUser, authd := getAuthUser(r)
176	if !authd {
177		renderError(w, "Forbidden", 403)
178		return
179	}
180	fileName := filepath.Clean(r.URL.Path[len("/delete/"):])
181	filePath := path.Join(c.FilesDirectory, authUser, fileName)
182	if r.Method == "POST" {
183		os.Remove(filePath) // suppress error
184	}
185	http.Redirect(w, r, "/my_site", 302)
186}
187
188func mySiteHandler(w http.ResponseWriter, r *http.Request) {
189	authUser, authd := getAuthUser(r)
190	if !authd {
191		renderError(w, "Forbidden", 403)
192		return
193	}
194	// check auth
195	files, _ := getUserFiles(authUser)
196	data := struct {
197		Host      string
198		PageTitle string
199		AuthUser  string
200		Files     []*File
201		LoggedIn  bool
202	}{c.Host, c.SiteTitle, authUser, files, authd}
203	_ = t.ExecuteTemplate(w, "my_site.html", data)
204}
205
206func loginHandler(w http.ResponseWriter, r *http.Request) {
207	if r.Method == "GET" {
208		// show page
209		data := struct {
210			Error     string
211			PageTitle string
212		}{"", "Login"}
213		err := t.ExecuteTemplate(w, "login.html", data)
214		if err != nil {
215			log.Println(err)
216			renderError(w, InternalServerErrorMsg, 500)
217			return
218		}
219	} else if r.Method == "POST" {
220		r.ParseForm()
221		name := r.Form.Get("username")
222		password := r.Form.Get("password")
223		row := DB.QueryRow("SELECT password_hash, active FROM user where username = $1", name)
224		var db_password []byte
225		var active bool
226		_ = row.Scan(&db_password, &active)
227		if db_password != nil && !active {
228			data := struct {
229				Error     string
230				PageTitle string
231			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
232			t.ExecuteTemplate(w, "login.html", data)
233			return
234		}
235		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
236			log.Println("logged in")
237			session, _ := SessionStore.Get(r, "cookie-session")
238			session.Values["auth_user"] = name
239			session.Save(r, w)
240			http.Redirect(w, r, "/", 302)
241		} else {
242			data := struct {
243				Error     string
244				PageTitle string
245			}{"Invalid login or password", c.SiteTitle}
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		}
253	}
254}
255
256func logoutHandler(w http.ResponseWriter, r *http.Request) {
257	session, _ := SessionStore.Get(r, "cookie-session")
258	session.Options.MaxAge = -1
259	session.Save(r, w)
260	http.Redirect(w, r, "/", 302)
261}
262
263const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
264
265func isOkUsername(s string) bool {
266	if len(s) < 1 {
267		return false
268	}
269	if len(s) > 31 {
270		return false
271	}
272	for _, char := range s {
273		if !strings.Contains(ok, strings.ToLower(string(char))) {
274			return false
275		}
276	}
277	return true
278}
279func registerHandler(w http.ResponseWriter, r *http.Request) {
280	if r.Method == "GET" {
281		data := struct {
282			Host      string
283			Errors    []string
284			PageTitle string
285		}{c.Host, nil, "Register"}
286		err := t.ExecuteTemplate(w, "register.html", data)
287		if err != nil {
288			log.Println(err)
289			renderError(w, InternalServerErrorMsg, 500)
290			return
291		}
292	} else if r.Method == "POST" {
293		r.ParseForm()
294		email := r.Form.Get("email")
295		password := r.Form.Get("password")
296		errors := []string{}
297		if !strings.Contains(email, "@") {
298			errors = append(errors, "Invalid Email")
299		}
300		if r.Form.Get("password") != r.Form.Get("password2") {
301			errors = append(errors, "Passwords don't match")
302		}
303		if len(password) < 6 {
304			errors = append(errors, "Password is too short")
305		}
306		username := strings.ToLower(r.Form.Get("username"))
307		if !isOkUsername(username) {
308			errors = append(errors, "Username is invalid: can only contain letters, numbers and hypens. Maximum 32 characters.")
309		}
310		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
311		if len(errors) == 0 {
312			_, err = DB.Exec("insert into user (username, email, password_hash) values ($1, $2, $3)", username, email, string(hashedPassword))
313			if err != nil {
314				log.Println(err)
315				errors = append(errors, "Username or email is already used")
316			}
317		}
318		if len(errors) > 0 {
319			data := struct {
320				Host      string
321				Errors    []string
322				PageTitle string
323			}{c.Host, errors, "Register"}
324			t.ExecuteTemplate(w, "register.html", data)
325		} else {
326			data := struct {
327				Host      string
328				Message   string
329				PageTitle string
330			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
331			t.ExecuteTemplate(w, "message.html", data)
332		}
333	}
334}
335
336// Server a user's file
337func userFile(w http.ResponseWriter, r *http.Request) {
338	userName := strings.Split(r.Host, ".")[0]
339	p := filepath.Clean(r.URL.Path)
340	if p == "/" {
341		p = "index.gmi"
342	}
343	fileName := path.Join(c.FilesDirectory, userName, p)
344	extension := path.Ext(fileName)
345	if r.URL.Path == "/style.css" {
346		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
347	}
348	query := r.URL.Query()
349	_, raw := query["raw"]
350	if !raw && (extension == ".gmi" || extension == ".gemini") {
351		_, err := os.Stat(fileName)
352		if err != nil {
353			renderError(w, "404: file not found", 404)
354			return
355		}
356		file, _ := os.Open(fileName)
357
358		htmlString := gmi.Parse(file).HTML()
359		data := struct {
360			SiteBody  template.HTML
361			PageTitle string
362		}{template.HTML(htmlString), userName}
363		t.ExecuteTemplate(w, "user_page.html", data)
364	} else {
365		http.ServeFile(w, r, fileName)
366	}
367}
368
369func runHTTPServer() {
370	log.Printf("Running http server on %s", c.Host)
371	var err error
372	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
373	if err != nil {
374		log.Fatal(err)
375	}
376	serveMux := http.NewServeMux()
377
378	s := strings.SplitN(c.Host, ":", 2)
379	hostname := s[0]
380	var port string
381	if len(s) > 1 {
382		port = s[1]
383	} else {
384		port = "443"
385	}
386	serveMux.HandleFunc(hostname+"/", rootHandler)
387	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
388	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
389	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
390	serveMux.HandleFunc(hostname+"/login", loginHandler)
391	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
392	serveMux.HandleFunc(hostname+"/register", registerHandler)
393	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
394
395	// TODO rate limit login https://github.com/ulule/limiter
396
397	wrapped := handlers.LoggingHandler(os.Stdout, serveMux)
398
399	// handle user files based on subdomain
400	serveMux.HandleFunc("/", userFile)
401	// login+register functions
402	srv := &http.Server{
403		ReadTimeout:  5 * time.Second,
404		WriteTimeout: 10 * time.Second,
405		IdleTimeout:  120 * time.Second,
406		Addr:         ":" + port,
407		// TLSConfig:    tlsConfig,
408		Handler: wrapped,
409	}
410	log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
411}