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