package main import ( "bytes" "database/sql" "fmt" gmi "git.sr.ht/~adnano/go-gemini" "github.com/gorilla/handlers" "github.com/gorilla/sessions" _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" "html/template" "io" "io/ioutil" "log" "mime" "net/http" "os" "path" "path/filepath" "strings" "time" ) var t *template.Template var DB *sql.DB var SessionStore *sessions.CookieStore func renderDefaultError(w http.ResponseWriter, statusCode int) { errorMsg := http.StatusText(statusCode) renderError(w, errorMsg, statusCode) } func renderError(w http.ResponseWriter, errorMsg string, statusCode int) { data := struct { PageTitle string StatusCode int ErrorMsg string }{"Error!", statusCode, errorMsg} err := t.ExecuteTemplate(w, "error.html", data) if err != nil { // Shouldn't happen probably http.Error(w, errorMsg, statusCode) } } func rootHandler(w http.ResponseWriter, r *http.Request) { // serve everything inside static directory if r.URL.Path != "/" { fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path)) _, err := os.Stat(fileName) if err != nil { renderDefaultError(w, http.StatusNotFound) return } http.ServeFile(w, r, fileName) // TODO better error handling return } authd, _, isAdmin := getAuthUser(r) indexFiles, err := getIndexFiles(isAdmin) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } allUsers, err := getActiveUserNames() if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } data := struct { Host string PageTitle string Files []*File Users []string LoggedIn bool IsAdmin bool }{c.Host, c.SiteTitle, indexFiles, allUsers, authd, isAdmin} err = t.ExecuteTemplate(w, "index.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } func editFileHandler(w http.ResponseWriter, r *http.Request) { ok, authUser, _ := getAuthUser(r) if !ok { renderDefaultError(w, http.StatusForbidden) return } fileName := filepath.Clean(r.URL.Path[len("/edit/"):]) isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text") filePath := path.Join(c.FilesDirectory, authUser, fileName) if r.Method == "GET" { err := checkIfValidFile(filePath, nil) if err != nil { log.Println(err) renderError(w, err.Error(), http.StatusBadRequest) return } // Create directories if dne f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) var fileBytes []byte if os.IsNotExist(err) || !isText { fileBytes = []byte{} err = nil } else { defer f.Close() fileBytes, err = ioutil.ReadAll(f) } if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } data := struct { FileName string FileText string PageTitle string AuthUser string Host string IsText bool }{fileName, string(fileBytes), c.SiteTitle, authUser, c.Host, isText} err = t.ExecuteTemplate(w, "edit_file.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } else if r.Method == "POST" { // get post body r.ParseForm() fileText := r.Form.Get("file_text") // Web form by default gives us CR LF newlines. // Unix files use just LF fileText = strings.ReplaceAll(fileText, "\r\n", "\n") fileBytes := []byte(fileText) err := checkIfValidFile(filePath, fileBytes) if err != nil { log.Println(err) renderError(w, err.Error(), http.StatusBadRequest) return } // create directories if dne os.MkdirAll(path.Dir(filePath), os.ModePerm) if userHasSpace(authUser, len(fileBytes)) { if isText { // Cant edit binary files here err = ioutil.WriteFile(filePath, fileBytes, 0644) } } else { renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest) return } if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } newName := filepath.Clean(r.Form.Get("rename")) err = checkIfValidFile(newName, fileBytes) if err != nil { log.Println(err) renderError(w, err.Error(), http.StatusBadRequest) return } if newName != fileName { newPath := path.Join(c.FilesDirectory, authUser, newName) os.MkdirAll(path.Dir(newPath), os.ModePerm) os.Rename(filePath, newPath) fileName = newName } http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther) } } func uploadFilesHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { session, _ := SessionStore.Get(r, "cookie-session") authUser, ok := session.Values["auth_user"].(string) if !ok { renderDefaultError(w, http.StatusForbidden) return } r.ParseMultipartForm(10 << 6) // why does this not work file, fileHeader, err := r.FormFile("file") fileName := filepath.Clean(fileHeader.Filename) defer file.Close() if err != nil { log.Println(err) renderError(w, err.Error(), http.StatusBadRequest) return } dest, _ := ioutil.ReadAll(file) err = checkIfValidFile(fileName, dest) if err != nil { log.Println(err) renderError(w, err.Error(), http.StatusBadRequest) return } destPath := path.Join(c.FilesDirectory, authUser, fileName) f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } defer f.Close() if userHasSpace(authUser, c.MaxFileBytes) { // Not quite right io.Copy(f, bytes.NewReader(dest)) } else { renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest) return } } http.Redirect(w, r, "/my_site", http.StatusSeeOther) } func getAuthUser(r *http.Request) (bool, string, bool) { session, _ := SessionStore.Get(r, "cookie-session") user, ok := session.Values["auth_user"].(string) isAdmin, _ := session.Values["admin"].(bool) return ok, user, isAdmin } func deleteFileHandler(w http.ResponseWriter, r *http.Request) { authd, authUser, _ := getAuthUser(r) if !authd { renderDefaultError(w, http.StatusForbidden) return } fileName := filepath.Clean(r.URL.Path[len("/delete/"):]) filePath := path.Join(c.FilesDirectory, authUser, fileName) if r.Method == "POST" { os.Remove(filePath) // suppress error } http.Redirect(w, r, "/my_site", http.StatusSeeOther) } func mySiteHandler(w http.ResponseWriter, r *http.Request) { authd, authUser, isAdmin := getAuthUser(r) if !authd { renderDefaultError(w, http.StatusForbidden) return } // check auth userFolder := path.Join(c.FilesDirectory, authUser) files, _ := getMyFilesRecursive(userFolder, authUser) data := struct { Host string PageTitle string AuthUser string Files []*File LoggedIn bool IsAdmin bool }{c.Host, c.SiteTitle, authUser, files, authd, isAdmin} _ = t.ExecuteTemplate(w, "my_site.html", data) } func myAccountHandler(w http.ResponseWriter, r *http.Request) { authd, authUser, isAdmin := getAuthUser(r) if !authd { renderDefaultError(w, http.StatusForbidden) return } me, _ := getUserByName(authUser) type pageData struct { PageTitle string LoggedIn bool AuthUser string IsAdmin bool Email string Errors []string } data := pageData{"My Account", true, authUser, isAdmin, me.Email, nil} if r.Method == "GET" { err := t.ExecuteTemplate(w, "me.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } else if r.Method == "POST" { r.ParseForm() newUsername := r.Form.Get("username") fmt.Println(newUsername) errors := []string{} newEmail := r.Form.Get("email") newUsername = strings.ToLower(newUsername) var err error if newEmail != me.Email { _, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Email) if err != nil { // TODO better error not sql errors = append(errors, err.Error()) } } if newUsername != authUser { // Rename User err = renameUser(authUser, newUsername) fmt.Println(newEmail, me.Email, newUsername, authUser) if err != nil { errors = append(errors, err.Error()) } else { session, _ := SessionStore.Get(r, "cookie-session") session.Values["auth_user"] = newUsername session.Save(r, w) } } // reset auth authd, authUser, isAdmin = getAuthUser(r) data.Errors = errors data.AuthUser = authUser data.Email = newEmail _ = t.ExecuteTemplate(w, "me.html", data) } } func archiveHandler(w http.ResponseWriter, r *http.Request) { authd, authUser, _ := getAuthUser(r) if !authd { renderDefaultError(w, http.StatusForbidden) return } if r.Method == "GET" { userFolder := filepath.Join(c.FilesDirectory, filepath.Clean(authUser)) err := zipit(userFolder, w) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } } func loginHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { // show page data := struct { Error string PageTitle string }{"", "Login"} err := t.ExecuteTemplate(w, "login.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } else if r.Method == "POST" { r.ParseForm() name := r.Form.Get("username") password := r.Form.Get("password") row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name) var db_password []byte var username string var active bool var isAdmin bool _ = row.Scan(&username, &db_password, &active, &isAdmin) if db_password != nil && !active { data := struct { Error string PageTitle string }{"Your account is not active yet. Pending admin approval", c.SiteTitle} t.ExecuteTemplate(w, "login.html", data) return } if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil { log.Println("logged in") session, _ := SessionStore.Get(r, "cookie-session") session.Values["auth_user"] = username session.Values["admin"] = isAdmin session.Save(r, w) http.Redirect(w, r, "/my_site", http.StatusSeeOther) } else { data := struct { Error string PageTitle string }{"Invalid login or password", c.SiteTitle} err := t.ExecuteTemplate(w, "login.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } } } func logoutHandler(w http.ResponseWriter, r *http.Request) { session, _ := SessionStore.Get(r, "cookie-session") session.Options.MaxAge = -1 session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) } const ok = "-0123456789abcdefghijklmnopqrstuvwxyz" func isOkUsername(s string) error { if len(s) < 1 { return fmt.Errorf("Username is too short") } if len(s) > 32 { return fmt.Errorf("Username is too long. 32 char max.") } for _, char := range s { if !strings.Contains(ok, strings.ToLower(string(char))) { return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.") } } return nil } func registerHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { data := struct { Host string Errors []string PageTitle string }{c.Host, nil, "Register"} err := t.ExecuteTemplate(w, "register.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } else if r.Method == "POST" { r.ParseForm() email := r.Form.Get("email") password := r.Form.Get("password") errors := []string{} if r.Form.Get("password") != r.Form.Get("password2") { errors = append(errors, "Passwords don't match") } if len(password) < 6 { errors = append(errors, "Password is too short") } username := strings.ToLower(r.Form.Get("username")) err := isOkUsername(username) if err != nil { errors = append(errors, err.Error()) } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error reference := r.Form.Get("reference") if len(errors) == 0 { _, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference) if err != nil { errors = append(errors, "Username or email is already used") } } if len(errors) > 0 { data := struct { Host string Errors []string PageTitle string }{c.Host, errors, "Register"} t.ExecuteTemplate(w, "register.html", data) } else { data := struct { Host string Message string PageTitle string }{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"} t.ExecuteTemplate(w, "message.html", data) } } } func adminHandler(w http.ResponseWriter, r *http.Request) { _, _, isAdmin := getAuthUser(r) if !isAdmin { renderDefaultError(w, http.StatusForbidden) return } allUsers, err := getUsers() if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } data := struct { Users []User LoggedIn bool IsAdmin bool PageTitle string Host string }{allUsers, true, true, "Admin", c.Host} err = t.ExecuteTemplate(w, "admin.html", data) if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } } func getFavicon(user string) string { faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt") content, err := ioutil.ReadFile(faviconPath) if err != nil { return "" } strcontent := []rune(string(content)) if len(strcontent) > 0 { return string(strcontent[0]) } return "" } // Server a user's file func userFile(w http.ResponseWriter, r *http.Request) { userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary p := filepath.Clean(r.URL.Path) var isDir bool fileName := path.Join(c.FilesDirectory, userName, p) stat, err := os.Stat(fileName) if stat != nil { isDir = stat.IsDir() } if p == "/" || isDir { fileName = path.Join(fileName, "index.gmi") } if strings.HasPrefix(p, "/.hidden") { renderDefaultError(w, http.StatusForbidden) return } if r.URL.Path == "/style.css" { http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css")) return } _, err = os.Stat(fileName) if os.IsNotExist(err) { renderDefaultError(w, http.StatusNotFound) return } // Dumb content negotiation extension := path.Ext(fileName) _, raw := r.URL.Query()["raw"] acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini") if !raw && !acceptsGemini && (extension == ".gmi" || extension == ".gemini") { file, _ := os.Open(fileName) htmlString := textToHTML(gmi.ParseText(file)) favicon := getFavicon(userName) data := struct { SiteBody template.HTML Favicon string PageTitle string }{template.HTML(htmlString), favicon, userName + p} t.ExecuteTemplate(w, "user_page.html", data) } else { http.ServeFile(w, r, fileName) } } func adminUserHandler(w http.ResponseWriter, r *http.Request) { _, _, isAdmin := getAuthUser(r) if r.Method == "POST" { if !isAdmin { renderDefaultError(w, http.StatusForbidden) return } components := strings.Split(r.URL.Path, "/") if len(components) < 5 { renderError(w, "Invalid action", http.StatusBadRequest) return } userName := components[3] action := components[4] var err error if action == "activate" { err = activateUser(userName) } else if action == "delete" { err = deleteUser(userName) } if err != nil { log.Println(err) renderDefaultError(w, http.StatusInternalServerError) return } http.Redirect(w, r, "/admin", http.StatusSeeOther) } } func runHTTPServer() { log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled) var err error t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html")) if err != nil { log.Fatal(err) } serveMux := http.NewServeMux() s := strings.SplitN(c.Host, ":", 2) hostname := s[0] port := c.HttpPort serveMux.HandleFunc(hostname+"/", rootHandler) serveMux.HandleFunc(hostname+"/my_site", mySiteHandler) serveMux.HandleFunc(hostname+"/me", myAccountHandler) serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler) serveMux.HandleFunc(hostname+"/admin", adminHandler) serveMux.HandleFunc(hostname+"/edit/", editFileHandler) serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler) serveMux.HandleFunc(hostname+"/login", loginHandler) serveMux.HandleFunc(hostname+"/logout", logoutHandler) serveMux.HandleFunc(hostname+"/register", registerHandler) serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler) // admin commands serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler) // TODO rate limit login https://github.com/ulule/limiter wrapped := handlers.LoggingHandler(log.Writer(), serveMux) // handle user files based on subdomain serveMux.HandleFunc("/", userFile) // login+register functions srv := &http.Server{ ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, Addr: fmt.Sprintf(":%d", port), // TLSConfig: tlsConfig, Handler: wrapped, } if c.HttpsEnabled { log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile)) } else { log.Fatal(srv.ListenAndServe()) } }