neko/server/internal/http/http.go

251 lines
6.6 KiB
Go
Raw Normal View History

2020-01-19 12:30:09 +13:00
package http
import (
"context"
2021-03-20 09:33:49 +13:00
"encoding/json"
2022-10-31 14:06:05 +13:00
"fmt"
2022-09-18 04:17:04 +12:00
"image/jpeg"
2022-11-17 14:06:36 +13:00
"io"
2020-01-19 12:30:09 +13:00
"net/http"
"os"
2022-10-31 14:06:05 +13:00
"regexp"
2022-09-18 04:17:04 +12:00
"strconv"
2020-01-19 12:30:09 +13:00
2023-10-16 00:18:43 +13:00
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
2022-11-20 08:33:03 +13:00
"github.com/go-chi/cors"
2020-01-19 12:30:09 +13:00
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2022-09-13 08:18:18 +12:00
"m1k1o/neko/internal/config"
2021-10-06 09:38:24 +13:00
"m1k1o/neko/internal/types"
2020-01-19 12:30:09 +13:00
)
2022-10-31 14:06:05 +13:00
const FILE_UPLOAD_BUF_SIZE = 65000
2020-01-19 12:30:09 +13:00
type Server struct {
logger zerolog.Logger
router *chi.Mux
http *http.Server
conf *config.Server
}
2022-09-18 04:17:04 +12:00
func New(conf *config.Server, webSocketHandler types.WebSocketHandler, desktop types.DesktopManager) *Server {
2021-03-20 09:33:49 +13:00
logger := log.With().Str("module", "http").Logger()
2020-01-19 12:30:09 +13:00
router := chi.NewRouter()
router.Use(middleware.RequestID) // Create a request ID for each request
2023-11-20 02:50:23 +13:00
if conf.Proxy {
router.Use(middleware.RealIP)
}
2021-10-06 10:13:44 +13:00
router.Use(middleware.RequestLogger(&logformatter{logger}))
router.Use(middleware.Recoverer) // Recover from panics without crashing server
2022-11-12 14:27:15 +13:00
router.Use(middleware.Compress(5, "application/octet-stream"))
2020-01-19 12:30:09 +13:00
2022-11-20 08:33:03 +13:00
router.Use(cors.Handler(cors.Options{
AllowOriginFunc: conf.AllowOrigin,
AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
2022-09-02 04:22:01 +12:00
if conf.PathPrefix != "/" {
router.Use(func(h http.Handler) http.Handler {
return http.StripPrefix(conf.PathPrefix, h)
})
}
2020-01-19 12:30:09 +13:00
router.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
2021-10-06 10:10:10 +13:00
err := webSocketHandler.Upgrade(w, r)
if err != nil {
logger.Warn().Err(err).Msg("failed to upgrade websocket conection")
}
2020-01-19 12:30:09 +13:00
})
2021-03-20 09:33:49 +13:00
router.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
password := r.URL.Query().Get("pwd")
isAdmin, err := webSocketHandler.IsAdmin(password)
if err != nil {
2021-10-06 10:10:10 +13:00
http.Error(w, err.Error(), http.StatusForbidden)
2021-03-20 09:33:49 +13:00
return
}
if !isAdmin {
2021-10-06 10:10:10 +13:00
http.Error(w, "bad authorization", http.StatusUnauthorized)
2021-03-20 09:33:49 +13:00
return
}
w.Header().Set("Content-Type", "application/json")
2021-03-20 10:06:40 +13:00
stats := webSocketHandler.Stats()
if err := json.NewEncoder(w).Encode(stats); err != nil {
2021-03-20 09:33:49 +13:00
logger.Warn().Err(err).Msg("failed writing json error response")
}
})
2022-09-18 04:17:04 +12:00
router.Get("/screenshot.jpg", func(w http.ResponseWriter, r *http.Request) {
password := r.URL.Query().Get("pwd")
isAdmin, err := webSocketHandler.IsAdmin(password)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
if !isAdmin {
http.Error(w, "bad authorization", http.StatusUnauthorized)
return
}
if webSocketHandler.IsLocked("login") {
http.Error(w, "room is locked", http.StatusLocked)
return
}
quality, err := strconv.Atoi(r.URL.Query().Get("quality"))
if err != nil {
quality = 90
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Content-Type", "image/jpeg")
img := desktop.GetScreenshotImage()
if err := jpeg.Encode(w, img, &jpeg.Options{Quality: quality}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
2022-11-20 08:26:45 +13:00
// allow downloading and uploading files
if webSocketHandler.FileTransferEnabled() {
router.Get("/file", func(w http.ResponseWriter, r *http.Request) {
password := r.URL.Query().Get("pwd")
isAuthorized, err := webSocketHandler.CanTransferFiles(password)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
2022-10-31 14:06:05 +13:00
2022-11-20 08:26:45 +13:00
if !isAuthorized {
http.Error(w, "bad authorization", http.StatusUnauthorized)
return
}
2022-10-31 14:06:05 +13:00
2022-11-20 08:26:45 +13:00
filename := r.URL.Query().Get("filename")
badChars, _ := regexp.MatchString(`(?m)\.\.(?:\/|$)`, filename)
if filename == "" || badChars {
http.Error(w, "bad filename", http.StatusBadRequest)
return
}
2022-10-31 14:06:05 +13:00
2022-11-20 08:26:45 +13:00
filePath := webSocketHandler.FileTransferPath(filename)
f, err := os.Open(filePath)
if err != nil {
http.Error(w, "not found or unable to open", http.StatusNotFound)
return
}
defer f.Close()
2022-10-31 14:06:05 +13:00
2022-11-20 08:26:45 +13:00
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
io.Copy(w, f)
})
2022-10-31 14:06:05 +13:00
2022-11-20 08:26:45 +13:00
router.Post("/file", func(w http.ResponseWriter, r *http.Request) {
password := r.URL.Query().Get("pwd")
isAuthorized, err := webSocketHandler.CanTransferFiles(password)
2022-10-31 14:06:05 +13:00
if err != nil {
2022-11-20 08:26:45 +13:00
http.Error(w, err.Error(), http.StatusForbidden)
2022-10-31 14:06:05 +13:00
return
}
2022-11-20 08:26:45 +13:00
if !isAuthorized {
http.Error(w, "bad authorization", http.StatusUnauthorized)
2022-10-31 14:06:05 +13:00
return
}
2022-11-20 08:26:45 +13:00
err = r.ParseMultipartForm(32 << 20)
if err != nil || r.MultipartForm == nil {
logger.Warn().Err(err).Msg("failed to parse multipart form")
http.Error(w, "error parsing form", http.StatusBadRequest)
return
}
2022-11-20 08:26:45 +13:00
for _, formheader := range r.MultipartForm.File["files"] {
filePath := webSocketHandler.FileTransferPath(formheader.Filename)
formfile, err := formheader.Open()
if err != nil {
logger.Warn().Err(err).Msg("failed to open formdata file")
http.Error(w, "error writing file", http.StatusInternalServerError)
return
}
defer formfile.Close()
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
http.Error(w, "unable to open file for writing", http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(f, formfile)
}
err = r.MultipartForm.RemoveAll()
if err != nil {
logger.Warn().Err(err).Msg("failed to remove multipart form")
}
2022-11-20 08:26:45 +13:00
})
}
2022-10-31 14:06:05 +13:00
2021-03-20 02:42:54 +13:00
router.Get("/health", func(w http.ResponseWriter, r *http.Request) {
2021-10-06 10:10:10 +13:00
_, _ = w.Write([]byte("true"))
2021-03-20 02:42:54 +13:00
})
2020-01-19 12:30:09 +13:00
fs := http.FileServer(http.Dir(conf.Static))
router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
2021-03-11 10:52:41 +13:00
if _, err := os.Stat(conf.Static + r.URL.Path); !os.IsNotExist(err) {
2020-01-19 12:30:09 +13:00
fs.ServeHTTP(w, r)
2021-03-11 10:08:04 +13:00
} else {
2021-10-06 10:10:10 +13:00
http.NotFound(w, r)
2020-01-19 12:30:09 +13:00
}
})
server := &http.Server{
Addr: conf.Bind,
Handler: router,
}
return &Server{
logger: logger,
router: router,
http: server,
conf: conf,
}
}
func (s *Server) Start() {
if s.conf.Cert != "" && s.conf.Key != "" {
go func() {
if err := s.http.ListenAndServeTLS(s.conf.Cert, s.conf.Key); err != http.ErrServerClosed {
s.logger.Panic().Err(err).Msg("unable to start https server")
}
}()
s.logger.Info().Msgf("https listening on %s", s.http.Addr)
} else {
go func() {
if err := s.http.ListenAndServe(); err != http.ErrServerClosed {
s.logger.Panic().Err(err).Msg("unable to start http server")
}
}()
s.logger.Warn().Msgf("http listening on %s", s.http.Addr)
}
}
func (s *Server) Shutdown() error {
return s.http.Shutdown(context.Background())
}