Cosmos-Server/src/httpServer.go

511 lines
16 KiB
Go
Raw Normal View History

2023-02-26 22:26:09 +00:00
package main
import (
"net/http"
2023-03-25 20:15:00 +00:00
"github.com/azukaar/cosmos-server/src/utils"
"github.com/azukaar/cosmos-server/src/user"
"github.com/azukaar/cosmos-server/src/configapi"
"github.com/azukaar/cosmos-server/src/proxy"
"github.com/azukaar/cosmos-server/src/docker"
2023-06-04 14:41:26 +00:00
"github.com/azukaar/cosmos-server/src/authorizationserver"
2023-06-09 18:48:31 +00:00
"github.com/azukaar/cosmos-server/src/market"
2023-08-20 10:36:52 +00:00
"github.com/azukaar/cosmos-server/src/constellation"
2023-10-26 14:40:07 +00:00
"github.com/azukaar/cosmos-server/src/metrics"
2023-02-26 22:26:09 +00:00
"github.com/gorilla/mux"
2023-03-10 20:59:56 +00:00
"strconv"
"time"
2023-03-12 18:17:28 +00:00
"os"
"strings"
2023-03-10 20:59:56 +00:00
"github.com/go-chi/chi/middleware"
"github.com/go-chi/httprate"
"crypto/tls"
2023-03-12 18:17:28 +00:00
spa "github.com/roberthodgen/spa-server"
"github.com/foomo/tlsconfig"
2023-07-01 15:32:21 +00:00
"context"
2023-02-26 22:26:09 +00:00
)
2023-03-10 20:59:56 +00:00
var serverPortHTTP = ""
var serverPortHTTPS = ""
2023-07-01 15:32:21 +00:00
var HTTPServer *http.Server
2023-07-06 10:07:17 +00:00
var HTTPServer2 *http.Server
func startHTTPServer(router *mux.Router) error {
HTTPServer2 = nil
HTTPServer = &http.Server{
Addr: "0.0.0.0:" + serverPortHTTP,
ReadTimeout: 0,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 0,
IdleTimeout: 30 * time.Second,
Handler: router,
DisableGeneralOptionsHandler: true,
2023-02-26 22:26:09 +00:00
}
2023-07-06 10:07:17 +00:00
docker.CheckPorts()
utils.Log("Listening to HTTP on : 0.0.0.0:" + serverPortHTTP)
return HTTPServer.ListenAndServe()
2023-02-26 22:26:09 +00:00
}
2023-07-06 10:07:17 +00:00
func startHTTPSServer(router *mux.Router) error {
2023-07-01 15:32:21 +00:00
//config := utils.GetMainConfig()
2023-06-23 14:29:54 +00:00
utils.IsHTTPS = true
2023-03-25 20:15:00 +00:00
// redirect http to https
go (func () {
2023-06-04 14:41:26 +00:00
httpRouter := mux.NewRouter()
httpRouter.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// change port in host
if strings.HasSuffix(r.Host, ":" + serverPortHTTP) {
if serverPortHTTPS != "443" {
r.Host = r.Host[:len(r.Host)-len(":" + serverPortHTTP)] + ":" + serverPortHTTPS
} else {
r.Host = r.Host[:len(r.Host)-len(":" + serverPortHTTP)]
2023-02-26 22:26:09 +00:00
}
}
http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently)
2023-06-04 14:41:26 +00:00
})
2023-07-06 10:07:17 +00:00
HTTPServer2 = &http.Server{
Addr: "0.0.0.0:" + serverPortHTTP,
ReadTimeout: 0,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 0,
IdleTimeout: 30 * time.Second,
Handler: httpRouter,
DisableGeneralOptionsHandler: true,
}
err := HTTPServer2.ListenAndServe()
2023-07-06 10:07:17 +00:00
if err != nil && err != http.ErrServerClosed {
utils.Fatal("Listening to HTTP (Redirecting to HTTPS)", err)
}
})()
2023-02-26 22:26:09 +00:00
utils.Log("Listening to HTTP on :" + serverPortHTTP)
utils.Log("Listening to HTTPS on :" + serverPortHTTPS)
2023-07-06 10:07:17 +00:00
config := utils.GetMainConfig()
HTTPConfig := config.HTTPConfig
2023-03-10 20:59:56 +00:00
2023-07-06 10:07:17 +00:00
var tlsCert = HTTPConfig.TLSCert
var tlsKey= HTTPConfig.TLSKey
2023-07-02 13:53:14 +00:00
2023-07-06 10:07:17 +00:00
tlsConf := tlsconfig.NewServerTLSConfig(tlsconfig.TLSModeServerStrict)
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
cert, errCert := tls.X509KeyPair(([]byte)(tlsCert), ([]byte)(tlsKey))
if errCert != nil {
config.HTTPConfig.ForceHTTPSCertificateRenewal = true
utils.SetBaseMainConfig(config)
utils.Fatal("Getting Certificate pair", errCert)
}
2023-02-26 22:26:09 +00:00
2023-07-06 10:07:17 +00:00
tlsConf.Certificates = []tls.Certificate{cert}
HTTPServer = &http.Server{
TLSConfig: tlsConf,
Addr: "0.0.0.0:" + serverPortHTTPS,
ReadTimeout: 0,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 0,
IdleTimeout: 30 * time.Second,
Handler: router,
DisableGeneralOptionsHandler: true,
}
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
// Redirect ports
docker.CheckPorts()
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
utils.Log("Now listening to HTTPS on :" + serverPortHTTPS)
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
return HTTPServer.ListenAndServeTLS("", "")
2023-02-26 22:26:09 +00:00
}
2023-03-10 20:59:56 +00:00
func tokenMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//Header.Del
r.Header.Del("x-cosmos-user")
r.Header.Del("x-cosmos-role")
r.Header.Del("x-cosmos-mfa")
2023-03-10 20:59:56 +00:00
u, err := user.RefreshUserToken(w, r)
if err != nil {
return
}
r.Header.Set("x-cosmos-user", u.Nickname)
r.Header.Set("x-cosmos-role", strconv.Itoa((int)(u.Role)))
r.Header.Set("x-cosmos-mfa", strconv.Itoa((int)(u.MFAState)))
2023-03-10 20:59:56 +00:00
next.ServeHTTP(w, r)
})
}
2023-11-07 16:26:51 +00:00
func SecureAPI(userRouter *mux.Router, public bool, publicCors bool) {
2023-06-04 14:41:26 +00:00
if(!public) {
userRouter.Use(tokenMiddleware)
}
userRouter.Use(proxy.SmartShieldMiddleware(
2023-07-25 10:38:12 +00:00
"__COSMOS",
2023-11-02 10:39:47 +00:00
utils.ProxyRouteConfig{
2023-11-05 15:16:57 +00:00
Name: "Cosmos-Internal",
2023-11-02 10:39:47 +00:00
SmartShield: utils.SmartShieldPolicy{
Enabled: true,
PolicyStrictness: 1,
2023-11-05 15:16:57 +00:00
PerUserRequestLimit: 6000,
2023-11-02 10:39:47 +00:00
},
2023-06-04 14:41:26 +00:00
},
))
2023-11-07 16:26:51 +00:00
if(publicCors || public) {
userRouter.Use(utils.PublicCORS)
}
2023-06-04 14:41:26 +00:00
userRouter.Use(utils.MiddlewareTimeout(45 * time.Second))
2023-11-07 16:26:51 +00:00
userRouter.Use(httprate.Limit(180, 1*time.Minute,
2023-06-04 14:41:26 +00:00
httprate.WithKeyFuncs(httprate.KeyByIP),
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
utils.Error("Too many requests. Throttling", nil)
utils.HTTPError(w, "Too many requests",
http.StatusTooManyRequests, "HTTP003")
return
}),
))
}
2023-11-06 19:57:04 +00:00
func CertificateIsExpiredSoon(validUntil time.Time) bool {
2023-07-01 15:32:21 +00:00
// allow 5 days of leeway
2023-11-06 19:57:04 +00:00
isValid := time.Now().Add(45 * 24 * time.Hour).Before(validUntil)
if !isValid {
utils.TriggerEvent(
"cosmos.proxy.certificate",
"Cosmos Certificate Expire Soon",
"warning",
"",
map[string]interface{}{
})
utils.Log("Certificate is not valid anymore. Needs refresh")
}
return isValid
}
func CertificateIsExpired(validUntil time.Time) bool {
// allow 5 days of leeway
isValid := time.Now().Before(validUntil)
2023-07-01 15:32:21 +00:00
if !isValid {
utils.Log("Certificate is not valid anymore. Needs refresh")
}
return isValid
}
func InitServer() *mux.Router {
utils.RestartHTTPServer = RestartServer
2023-03-10 20:59:56 +00:00
baseMainConfig := utils.GetBaseMainConfig()
config := utils.GetMainConfig()
HTTPConfig := config.HTTPConfig
serverPortHTTP = HTTPConfig.HTTPPort
serverPortHTTPS = HTTPConfig.HTTPSPort
var tlsCert = HTTPConfig.TLSCert
var tlsKey= HTTPConfig.TLSKey
2023-02-26 22:26:09 +00:00
2023-07-02 12:00:29 +00:00
domains := utils.GetAllHostnames(true, true)
oldDomains := baseMainConfig.HTTPConfig.TLSKeyHostsCached
2023-07-01 15:32:21 +00:00
falledBack := false
2023-11-06 19:57:04 +00:00
NeedsRefresh := baseMainConfig.HTTPConfig.ForceHTTPSCertificateRenewal || (tlsCert == "" || tlsKey == "") || utils.HasAnyNewItem(domains, oldDomains) || !CertificateIsExpiredSoon(baseMainConfig.HTTPConfig.TLSValidUntil)
2023-07-01 15:32:21 +00:00
// If we have a certificate, we can fallback to it if necessary
CanFallback := tlsCert != "" && tlsKey != "" &&
len(config.HTTPConfig.TLSKeyHostsCached) > 0 &&
config.HTTPConfig.TLSKeyHostsCached[0] == config.HTTPConfig.Hostname &&
2023-11-06 19:57:04 +00:00
CertificateIsExpired(baseMainConfig.HTTPConfig.TLSValidUntil)
2023-07-01 15:32:21 +00:00
if(NeedsRefresh && config.HTTPConfig.HTTPSCertificateMode == utils.HTTPSCertModeList["LETSENCRYPT"]) {
if(config.HTTPConfig.DNSChallengeProvider != "") {
newEnv := config.HTTPConfig.DNSChallengeConfig
for key, value := range newEnv {
os.Setenv(key, value)
}
}
// Get Certificates
pub, priv := utils.DoLetsEncrypt()
if(pub == "" || priv == "") {
if(!CanFallback) {
utils.Error("Getting TLS certificate. Fallback to SELFSIGNED certificates", nil)
HTTPConfig.HTTPSCertificateMode = utils.HTTPSCertModeList["SELFSIGNED"]
falledBack = true
} else {
utils.Error("Getting TLS certificate. Fallback to previous certificate", nil)
}
} else {
baseMainConfig.HTTPConfig.TLSCert = pub
baseMainConfig.HTTPConfig.TLSKey = priv
baseMainConfig.HTTPConfig.TLSKeyHostsCached = domains
baseMainConfig.HTTPConfig.TLSValidUntil = time.Now().AddDate(0, 0, 90)
baseMainConfig.HTTPConfig.ForceHTTPSCertificateRenewal = false
utils.SetBaseMainConfig(baseMainConfig)
utils.Log("Saved new LETSENCRYPT TLS certificate")
2023-11-06 19:57:04 +00:00
utils.TriggerEvent(
"cosmos.proxy.certificate",
"Cosmos Certificate Renewed",
"important",
"",
map[string]interface{}{
"domains": domains,
})
utils.WriteNotification(utils.Notification{
Recipient: "admin",
Title: "Cosmos Certificate Renewed",
Message: "The TLS certificate for the following domains has been renewed: " + strings.Join(domains, ", "),
Level: "info",
})
2023-07-01 15:32:21 +00:00
tlsCert = pub
tlsKey = priv
}
}
if(NeedsRefresh && HTTPConfig.HTTPSCertificateMode == utils.HTTPSCertModeList["SELFSIGNED"]) {
2023-06-23 14:29:54 +00:00
utils.Log("Generating new TLS certificate for domains: " + strings.Join(domains, ", "))
pub, priv := utils.GenerateRSAWebCertificates(domains)
2023-03-10 20:59:56 +00:00
2023-07-01 15:32:21 +00:00
if !falledBack {
baseMainConfig.HTTPConfig.TLSCert = pub
baseMainConfig.HTTPConfig.TLSKey = priv
baseMainConfig.HTTPConfig.TLSKeyHostsCached = domains
baseMainConfig.HTTPConfig.TLSValidUntil = time.Now().AddDate(0, 0, 364)
baseMainConfig.HTTPConfig.ForceHTTPSCertificateRenewal = false
utils.SetBaseMainConfig(baseMainConfig)
utils.Log("Saved new SELFISGNED TLS certificate")
2023-11-06 19:57:04 +00:00
utils.TriggerEvent(
"cosmos.proxy.certificate",
"Cosmos Certificate Renewed",
"important",
"",
map[string]interface{}{
"domains": domains,
})
utils.WriteNotification(utils.Notification{
Recipient: "admin",
Title: "Cosmos Certificate Renewed",
Message: "The TLS certificate for the following domains has been renewed: " + strings.Join(domains, ", "),
Level: "info",
})
2023-07-01 15:32:21 +00:00
}
2023-03-10 20:59:56 +00:00
tlsCert = pub
tlsKey = priv
2023-02-26 22:26:09 +00:00
}
if ((HTTPConfig.AuthPublicKey == "" || HTTPConfig.AuthPrivateKey == "") && HTTPConfig.GenerateMissingAuthCert) {
2023-03-10 20:59:56 +00:00
utils.Log("Generating new Auth ED25519 certificate")
pub, priv := utils.GenerateEd25519Certificates()
baseMainConfig.HTTPConfig.AuthPublicKey = pub
baseMainConfig.HTTPConfig.AuthPrivateKey = priv
utils.SetBaseMainConfig(baseMainConfig)
utils.Log("Saved new Auth ED25519 certificate")
2023-02-26 22:26:09 +00:00
}
2023-07-01 15:32:21 +00:00
utils.Log("Initialising HTTP(S) Router and all routes")
2023-03-12 18:17:28 +00:00
router := mux.NewRouter().StrictSlash(true)
2023-11-02 16:52:27 +00:00
router.Use(utils.BlockBannedIPs)
2023-02-26 22:26:09 +00:00
2023-03-10 20:59:56 +00:00
router.Use(middleware.Logger)
if config.BlockedCountries != nil && len(config.BlockedCountries) > 0 {
2023-08-11 09:18:24 +00:00
router.Use(utils.BlockByCountryMiddleware(config.BlockedCountries, config.CountryBlacklistIsWhitelist))
}
2023-03-12 18:17:28 +00:00
2023-11-05 20:34:17 +00:00
logoAPI := router.PathPrefix("/logo").Subrouter()
2023-11-07 16:26:51 +00:00
SecureAPI(logoAPI, true, true)
2023-11-05 20:34:17 +00:00
logoAPI.HandleFunc("/", SendLogo)
2023-03-12 18:17:28 +00:00
srapi := router.PathPrefix("/cosmos").Subrouter()
2023-11-15 15:32:26 +00:00
srapi.HandleFunc("/api/login", user.UserLogin)
srapi.HandleFunc("/api/password-reset", user.ResetPassword)
srapi.HandleFunc("/api/mfa", user.API2FA)
2023-03-10 20:59:56 +00:00
2023-06-04 14:41:26 +00:00
srapi.HandleFunc("/api/dns", GetDNSRoute)
srapi.HandleFunc("/api/dns-check", CheckDNSRoute)
2023-08-10 15:53:12 +00:00
srapi.Use(utils.SetSecurityHeaders)
2023-06-04 14:41:26 +00:00
2023-03-29 20:38:50 +00:00
srapi.HandleFunc("/api/status", StatusRoute)
2023-05-01 10:00:45 +00:00
srapi.HandleFunc("/api/can-send-email", CanSendEmail)
2023-04-27 18:29:26 +00:00
srapi.HandleFunc("/api/favicon", GetFavicon)
srapi.HandleFunc("/api/ping", PingURL)
2023-03-29 20:38:50 +00:00
srapi.HandleFunc("/api/newInstall", NewInstallRoute)
2023-03-12 18:17:28 +00:00
srapi.HandleFunc("/api/logout", user.UserLogout)
srapi.HandleFunc("/api/register", user.UserRegister)
srapi.HandleFunc("/api/invite", user.UserResendInviteLink)
srapi.HandleFunc("/api/me", user.Me)
2023-03-16 18:56:36 +00:00
srapi.HandleFunc("/api/config", configapi.ConfigRoute)
srapi.HandleFunc("/api/restart", configapi.ConfigApiRestart)
2023-03-10 20:59:56 +00:00
2023-03-12 18:17:28 +00:00
srapi.HandleFunc("/api/users/{nickname}", user.UsersIdRoute)
srapi.HandleFunc("/api/users", user.UsersRoute)
2023-05-06 18:25:10 +00:00
2023-05-14 14:48:15 +00:00
srapi.HandleFunc("/api/images/pull-if-missing", docker.PullImageIfMissing)
srapi.HandleFunc("/api/images/pull", docker.PullImage)
srapi.HandleFunc("/api/images", docker.InspectImageRoute)
2023-05-13 17:38:39 +00:00
2023-05-06 18:25:10 +00:00
srapi.HandleFunc("/api/volume/{volumeName}", docker.DeleteVolumeRoute)
2023-05-07 16:47:20 +00:00
srapi.HandleFunc("/api/volumes", docker.VolumesRoute)
2023-05-06 18:25:10 +00:00
srapi.HandleFunc("/api/network/{networkID}", docker.DeleteNetworkRoute)
2023-05-07 16:47:20 +00:00
srapi.HandleFunc("/api/networks", docker.NetworkRoutes)
2023-03-25 20:15:00 +00:00
2023-05-05 18:05:33 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/manage/{action}", docker.ManageContainerRoute)
2023-03-31 19:19:38 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/secure/{status}", docker.SecureContainerRoute)
2023-05-16 17:08:01 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/auto-update/{status}", docker.AutoUpdateContainerRoute)
2023-05-06 18:25:10 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/logs", docker.GetContainerLogsRoute)
2023-05-11 18:15:05 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/terminal/{action}", docker.TerminalRoute)
2023-05-07 16:47:20 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/update", docker.UpdateContainerRoute)
2023-05-06 18:25:10 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/", docker.GetContainerRoute)
2023-05-07 16:47:20 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/network/{networkId}", docker.NetworkContainerRoutes)
srapi.HandleFunc("/api/servapps/{containerId}/networks", docker.NetworkContainerRoutes)
2023-05-14 14:48:15 +00:00
srapi.HandleFunc("/api/servapps/{containerId}/check-update", docker.CanUpdateImageRoute)
2023-03-25 20:15:00 +00:00
srapi.HandleFunc("/api/servapps", docker.ContainersRoute)
2023-05-13 17:38:39 +00:00
srapi.HandleFunc("/api/docker-service", docker.CreateServiceRoute)
2023-06-04 14:41:26 +00:00
2023-06-09 18:48:31 +00:00
srapi.HandleFunc("/api/markets", market.MarketGet)
2023-06-04 14:41:26 +00:00
2023-11-24 13:03:23 +00:00
srapi.HandleFunc("/api/upload/{name}", UploadImage)
srapi.HandleFunc("/api/image/{name}", GetImage)
2023-06-20 17:34:06 +00:00
2023-11-01 13:58:25 +00:00
srapi.HandleFunc("/api/get-backup", configapi.BackupFileApiGet)
2023-08-20 10:36:52 +00:00
srapi.HandleFunc("/api/constellation/devices", constellation.ConstellationAPIDevices)
2023-08-27 14:21:13 +00:00
srapi.HandleFunc("/api/constellation/restart", constellation.API_Restart)
2023-09-22 17:10:43 +00:00
srapi.HandleFunc("/api/constellation/reset", constellation.API_Reset)
srapi.HandleFunc("/api/constellation/connect", constellation.API_ConnectToExisting)
2023-08-27 14:21:13 +00:00
srapi.HandleFunc("/api/constellation/config", constellation.API_GetConfig)
srapi.HandleFunc("/api/constellation/logs", constellation.API_GetLogs)
2023-10-02 15:22:18 +00:00
srapi.HandleFunc("/api/constellation/block", constellation.DeviceBlock)
2023-03-10 20:59:56 +00:00
2023-11-06 19:57:04 +00:00
srapi.HandleFunc("/api/events", metrics.API_ListEvents)
2023-10-26 14:40:07 +00:00
srapi.HandleFunc("/api/metrics", metrics.API_GetMetrics)
2023-10-29 16:19:43 +00:00
srapi.HandleFunc("/api/reset-metrics", metrics.API_ResetMetrics)
2023-11-05 15:16:57 +00:00
srapi.HandleFunc("/api/list-metrics", metrics.ListMetrics)
srapi.HandleFunc("/api/notifications/read", utils.MarkAsRead)
srapi.HandleFunc("/api/notifications", utils.NotifGet)
2023-10-26 14:40:07 +00:00
2023-05-06 18:25:10 +00:00
if(!config.HTTPConfig.AcceptAllInsecureHostname) {
srapi.Use(utils.EnsureHostname)
}
2023-11-15 15:32:26 +00:00
srapi.Use(utils.EnsureHostnameCosmosAPI)
2023-05-05 18:05:33 +00:00
2023-11-07 16:26:51 +00:00
SecureAPI(srapi, false, false)
2023-03-12 18:17:28 +00:00
pwd,_ := os.Getwd()
utils.Log("Starting in " + pwd)
if _, err := os.Stat(pwd + "/static"); os.IsNotExist(err) {
utils.Fatal("Static folder not found at " + pwd + "/static", err)
}
2023-03-16 18:56:36 +00:00
2023-05-05 18:05:33 +00:00
2023-03-12 18:17:28 +00:00
fs := spa.SpaHandler(pwd + "/static", "index.html")
2023-05-05 18:05:33 +00:00
2023-05-06 18:25:10 +00:00
if(!config.HTTPConfig.AcceptAllInsecureHostname) {
fs = utils.EnsureHostname(fs)
}
2023-05-05 18:05:33 +00:00
2023-06-13 01:03:18 +00:00
router.PathPrefix("/cosmos-ui").Handler(http.StripPrefix("/cosmos-ui", fs))
2023-03-12 18:17:28 +00:00
router = proxy.BuildFromConfig(router, HTTPConfig.ProxyConfig)
2023-04-01 16:49:54 +00:00
router.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2023-07-01 16:06:12 +00:00
http.Redirect(w, r, "/cosmos-ui", http.StatusTemporaryRedirect)
2023-04-01 16:49:54 +00:00
}))
2023-03-10 20:59:56 +00:00
2023-06-04 14:41:26 +00:00
userRouter := router.PathPrefix("/oauth2").Subrouter()
2023-11-07 16:26:51 +00:00
SecureAPI(userRouter, false, true)
2023-06-04 14:41:26 +00:00
serverRouter := router.PathPrefix("/oauth2").Subrouter()
2023-11-07 16:26:51 +00:00
SecureAPI(serverRouter, true, true)
2023-06-04 14:41:26 +00:00
2023-10-14 21:37:18 +00:00
wellKnownRouter := router.PathPrefix("/").Subrouter()
2023-11-07 16:26:51 +00:00
SecureAPI(wellKnownRouter, true, true)
2023-06-04 14:41:26 +00:00
authorizationserver.RegisterHandlers(wellKnownRouter, userRouter, serverRouter)
2023-07-01 15:32:21 +00:00
return router
}
func StartServer() {
2023-07-01 15:46:25 +00:00
router := InitServer()
2023-07-06 10:07:17 +00:00
// start https server
var errServ error
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
for(errServ == http.ErrServerClosed || errServ == nil) {
config := utils.GetMainConfig()
HTTPConfig := config.HTTPConfig
var tlsCert = HTTPConfig.TLSCert
var tlsKey= HTTPConfig.TLSKey
2023-07-01 15:32:21 +00:00
2023-07-06 10:07:17 +00:00
if (
(
HTTPConfig.HTTPSCertificateMode == utils.HTTPSCertModeList["SELFSIGNED"] ||
HTTPConfig.HTTPSCertificateMode == utils.HTTPSCertModeList["PROVIDED"] ||
HTTPConfig.HTTPSCertificateMode == utils.HTTPSCertModeList["LETSENCRYPT"]) &&
tlsCert != "" && tlsKey != "") {
utils.Log("TLS certificate exist, starting HTTPS servers and redirecting HTTP to HTTPS")
errServ = startHTTPSServer(router)
} else {
utils.Log("TLS certificates do not exists or are disabled, starting HTTP server only")
errServ = startHTTPServer(router)
}
if errServ != nil && errServ != http.ErrServerClosed {
utils.Fatal("Listening to HTTPS", errServ)
}
utils.Log("HTTPS Server closed. Restarting.")
errServ = nil
router = InitServer()
2023-02-26 22:26:09 +00:00
}
}
2023-07-01 15:32:21 +00:00
func RestartServer() {
2023-07-02 14:47:29 +00:00
utils.LetsEncryptErrors = []string{}
2023-07-10 12:41:30 +00:00
IconCache = map[string]CachedImage{}
2023-07-01 15:32:21 +00:00
utils.Log("Restarting HTTP Server...")
LoadConfig()
go func() {
2023-07-06 10:07:17 +00:00
if HTTPServer2 != nil {
HTTPServer2.Shutdown(context.Background())
}
2023-07-01 15:32:21 +00:00
HTTPServer.Shutdown(context.Background())
}()
2023-07-02 12:00:29 +00:00
utils.Log("HTTPServer shutdown.")
2023-07-01 15:32:21 +00:00
}