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