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