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