package server import ( "database/sql" "errors" "fmt" "html/template" "log" "net/http" "strings" "sync" "sync/atomic" "time" mw "pageswiki/internal/server/middleware" routespkg "pageswiki/internal/server/routes" "pageswiki/internal/calendar" "pageswiki/internal/dregarnuhr" "pageswiki/internal/store" ) type Server struct { geckoOnce sync.Once gecko *geckoProxy calendarOnce sync.Once calendarRepo *calendar.Repository calendarErr error navigationCache navigationDataCache mux *http.ServeMux templates *template.Template store *store.Store previewSlots chan struct{} smtpSlots chan struct{} ldapSlots chan struct{} ldapDial ldapDialFunc previewRoot string diagramRoot string importRoot string schedulerWake chan struct{} foregroundRequests atomic.Int64 schedulerRunning atomic.Int64 schedulerOnce sync.Once schedulerRunner *dregarnuhr.Runner eventHandlersOnce sync.Once eventHandlers *dregarnuhr.Registry } func New( st *store.Store, ) *Server { s := &Server{ mux: http.NewServeMux(), store: st, previewSlots: make(chan struct{}, 1), smtpSlots: make(chan struct{}, 2), ldapSlots: make(chan struct{}, 4), ldapDial: dialLDAPDirectory, schedulerWake: make(chan struct{}, 1), } if !st.ReadOnly { s.initializePreviewScheduler() s.initializeImportRoot() } s.mustLoadTemplates() s.registerStaticRoutes() s.mux.HandleFunc("/_/api/v1/editor/state", s.handleEditorState) s.mux.HandleFunc("/_/api/v1/editor/convert", s.handleEditorConvert) s.mux.HandleFunc( "/o/e/", s.handleObjectEdit, ) s.mux.HandleFunc( "/o/r/", s.handleObjectRevisionHistory, ) s.mux.HandleFunc( "/o/", func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/o/uuid:") { s.handleObjectView(w, r) return } s.handleObjectRoute(w, r) }, ) s.mux.HandleFunc( "/r/history/", s.handleRevisionBrowser, ) s.mux.HandleFunc( "/r/view/", s.handleRevisionView, ) s.mux.HandleFunc( "/r/diff/", s.handleRevisionDiff, ) s.registerRoutes() if !st.ReadOnly && !st.BackgroundJobsDisabled { s.startGCWorker() s.startEventScheduler() } return s } func (s *Server) registerStaticRoutes() { s.mux.HandleFunc(socialImagePath, handleSocialImage) staticFS := http.FileServer( http.Dir("./static"), ) s.mux.Handle( "/static/", http.StripPrefix( "/static/", staticFS, ), ) themeFS := http.FileServer( http.Dir("/data/themes"), ) s.mux.Handle( "/-/theme/", http.StripPrefix( "/-/theme/", themeFS, ), ) } func (s *Server) mustLoadTemplates() { funcs := template.FuncMap{ "cspNonce": func() string { return "" }, "parentPath": parentPath, "T": s.T, "sub": func(a, b int) int { return a - b }, "add": func(a, b int) int { return a + b }, "mulFloat": func(a, b float64) float64 { return a * b }, "until": func(n int) []int { out := make([]int, n) for i := 0; i < n; i++ { out[i] = i } return out }, "formatBytes": func(n int) string { if n < 1024 { return fmt.Sprintf("%d B", n) } if n < 1024*1024 { return fmt.Sprintf("%.1f KiB", float64(n)/1024.0) } return fmt.Sprintf("%.1f MiB", float64(n)/(1024.0*1024.0)) }, "formatUnix": func(ts int64) string { if ts <= 0 { return "-" } return time. Unix(ts, 0). In(s.getLocation()). Format("2006-01-02 15:04") }, "formatUnixMS": func(ts int64) string { if ts <= 0 { return "-" } return time.UnixMilli(ts).In(s.getLocation()).Format("2006-01-02 15:04") }, } tmpl := template.New("").Funcs(funcs) parsed, err := parseTrustedTemplates(tmpl) if err != nil { panic(err) } s.templates = parsed } func (s *Server) registerRoutes() { s.registerCalendarRoutes() s.registerTaskRoutes() s.mux.HandleFunc("/_/auth/", s.handleAuth) s.mux.HandleFunc("/_/auth/profile", s.handleProfile) s.mux.HandleFunc("/_/obj/", s.handleImmutableObject) s.mux.HandleFunc("/v/json/", s.handleJSONStructure) s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI) s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI) s.mux.HandleFunc("/_/api/v1/browser/navigation", s.handleBrowserNavigationAPI) s.mux.HandleFunc("/u/", s.handleUserProfile) s.mux.HandleFunc("/g", s.handleGroups) s.mux.HandleFunc("/g/", s.handleGroups) s.mux.HandleFunc("/_/api/v1/city/", s.handleCityAPI) s.mux.HandleFunc("/v/import", s.handleImport) s.mux.HandleFunc("/v/import/", s.handleImport) s.mux.HandleFunc("/_/api/v1/import/", s.handleImportAPI) s.mux.HandleFunc("/-/sys/config/auth", s.handleAuthAdmin) s.mux.Handle(adapterGatewayPrefix+"/", newAdapterGatewayProxy()) routespkg.RegisterUIRoutes( s.mux, routespkg.UIHandlers{ Home: s.handleHome, NewPage: s.handleNewPage, SemanticEditor: s.handleEditorRoute, SemanticPage: s.handleSemanticRoute, RawView: s.handleRawView, TextWindow: s.handleTextWindow, LinkManager: s.handleLinkManager, Health: s.handleHealth, Tree: s.handleTree, Browser: s.handleBrowser, Preview: s.handlePreview, PlainView: s.handlePlainView, MarkdownView: s.handleMarkdownView, Slides: s.handleSlides, CompileMarkdown: s.handleCompileMarkdown, CompileDiagram: s.handleCompileDiagram, Config: s.handleConfig, AdapterConfig: s.handleAdapterPluginConfig, VimConfig: s.handleVimSettings, SystemExtensions: s.handleSystemExtensions, Periodical: s.handlePeriodical, Upload: s.handleUpload, Children: s.handleChildrenProjection, Bookmarks: s.handleBookmarkChildren, PreviewCache: s.handlePreviewCache, Search: s.handleSearch, Archive: s.handleArchiveEntry, EmailHTML: s.handleEmailHTML, PDFPage: s.handlePDFPage, OpenWith: s.handleOpenWith, City: s.handleCityMap, Print: s.handlePrint, Notifications: s.handleNotificationsPage, }, ) routespkg.RegisterAPIRoutes( s.mux, routespkg.APIHandlers{ CreateObject: s.handleCreateObjectAPI, ListObjects: s.handleListObjectsAPI, DeleteObject: s.handleDeleteObjectAPI, SaveRevision: s.handleSaveRevisionAPI, ListRevisions: s.handleRevisionListAPI, RestoreRevision: s.handleRestoreRevisionAPI, RenderMarkdown: s.handleMarkdownRenderAPI, AddTag: s.handleTagAddAPI, BindPath: s.handleBindPathAPI, RenamePath: s.handleRenamePath, RenamePreview: s.handleRenamePreview, RemovePath: s.handleRemovePathAPI, CopyPath: s.handleCopyPathAPI, ZombieList: s.handleZombieListAPI, ZombiePurge: s.handleZombiePurgeAPI, FederationEnroll: s.handleFederationEnrollAPI, Event: s.handleEventAPI, Queue: s.handleQueueAPI, Adapter: s.handleAdapterAPI, AdapterSession: s.handleAdapterSessionAPI, Notifications: s.handleNotificationsAPI, Publication: s.handlePublicationApprovalAPI, SearchSuggest: s.handleSearchSuggestAPI, }, ) } func (s *Server) handler() http.Handler { var h http.Handler = s.mux h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/_/api/v1/federation/enroll" || strings.HasPrefix(r.URL.Path, "/_/api/v1/adapter/session/") || strings.HasPrefix(r.URL.Path, adapterGatewayPrefix+"/") || r.URL.Path == "/health" { s.mux.ServeHTTP(w, r) return } domain, err := s.domainForRequestWithError(r) if err != nil { if errors.Is(err, sql.ErrNoRows) { http.NotFound(w, r) return } logDomainLookupError(r, err) http.Error( w, "domain lookup temporarily unavailable", http.StatusServiceUnavailable, ) return } if domain == nil { http.NotFound(w, r) return } if domain.Placement == "remote" { http.Error( w, "remote domain is not served by this instance", http.StatusMisdirectedRequest, ) return } s.mux.ServeHTTP(w, r) }) domainHandler := h h = s.withAuthorization(h) domainHandler = h h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { background := r.URL.Query().Get("preview") == "1" || strings.HasPrefix(r.URL.Path, "/v/preview-cache/") || r.URL.Path == feedsAPI+"browser/wisp/" if !background { s.foregroundRequests.Add(1) defer s.foregroundRequests.Add(-1) } domainHandler.ServeHTTP(w, r) }) h = s.withStandbyReadOnly(h) h = mw.NormalizePath(h) h = mw.RequestID(h) h = mw.Logging(h) h = mw.Recovery(h) return h } func (s *Server) Run(addr string) error { log.Printf( "listen %s", addr, ) return http.ListenAndServe( addr, s.handler(), ) }