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