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