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