main.router.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package main
  2. /*
  3. ArOZ Online System Main Request Router
  4. This is used to check authentication before actually serving file to the target client
  5. This function also handle the special page (login.html and user.html) delivery
  6. */
  7. import (
  8. "net/http"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. fs "imuslab.com/arozos/mod/filesystem"
  13. "imuslab.com/arozos/mod/locale"
  14. "imuslab.com/arozos/mod/network/gzipmiddleware"
  15. "imuslab.com/arozos/mod/permission"
  16. "imuslab.com/arozos/mod/utils"
  17. )
  18. func mrouter(h http.Handler) http.Handler {
  19. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. /*
  21. You can also check the path for url using r.URL.Path
  22. */
  23. //Container apps come first: an app hostname, /app/<slug>/, or a root
  24. //request made by an app page (which must never be answered from the
  25. //ArozOS web root, not even the public /script or /img paths below)
  26. if appProxyManager != nil && appProxyManager.HandleRequest(w, r) {
  27. return
  28. }
  29. if r.URL.Path == "/favicon.ico" || r.URL.Path == "/manifest.webmanifest" || r.URL.Path == "/robots.txt" || r.URL.Path == "/humans.txt" {
  30. //Serving web specification files. Allow no auth access.
  31. h.ServeHTTP(w, r)
  32. } else if r.URL.Path == "/login.html" {
  33. //Login page. Require special treatment for template.
  34. //Get the redirection address from the request URL
  35. red, _ := utils.GetPara(r, "redirect")
  36. //Append the redirection addr into the template
  37. imgsrc := filepath.Join(vendorResRoot, "auth_icon.png")
  38. if !fs.FileExists(imgsrc) {
  39. imgsrc = "./web/img/public/auth_icon.png"
  40. }
  41. imageBase64, _ := utils.LoadImageAsBase64(imgsrc)
  42. parsedPage, err := utils.Templateload("web/login.html", map[string]string{
  43. "redirection_addr": red,
  44. "usercount": strconv.Itoa(authAgent.GetUserCounts()),
  45. "service_logo": imageBase64,
  46. "login_addr": "system/auth/login",
  47. })
  48. if err != nil {
  49. panic("Error. Unable to parse login page. Is web directory data exists?")
  50. }
  51. w.Header().Add("Content-Type", "text/html; charset=UTF-8")
  52. w.Write([]byte(parsedPage))
  53. } else if r.URL.Path == "/reset.html" && authAgent.GetUserCounts() > 0 {
  54. //Password restart page. Allow access only when user number > 0
  55. system_resetpw_handlePasswordReset(w, r)
  56. } else if r.URL.Path == "/user.html" && authAgent.GetUserCounts() == 0 {
  57. //Serve user management page. This only allows serving of such page when the total usercount = 0 (aka System Initiation)
  58. h.ServeHTTP(w, r)
  59. } else if (len(r.URL.Path) > 11 && r.URL.Path[:11] == "/img/public") || (len(r.URL.Path) > 7 && r.URL.Path[:7] == "/script") {
  60. //Public image directory. Allow anyone to access resources inside this directory.
  61. if filepath.Ext("web"+fs.DecodeURI(r.RequestURI)) == ".js" {
  62. //Fixed serve js meme type invalid bug on Firefox
  63. w.Header().Add("Content-Type", "application/javascript; charset=UTF-8")
  64. }
  65. h.ServeHTTP(w, r)
  66. } else if len(r.URL.Path) >= len("/cluster/acn") && r.URL.Path[:12] == "/cluster/acn" {
  67. //Cluster node-to-node protocol (ACN). Requests are authenticated by
  68. //node signatures, not user sessions, see mod/cluster/acn
  69. if clusterManager == nil {
  70. //Cluster disabled (-disable_cluster) or its agent failed to start
  71. http.NotFound(w, r)
  72. return
  73. }
  74. clusterManager.ACNHandler().ServeHTTP(w, r)
  75. } else if len(r.URL.Path) >= len("/caldav") && r.URL.Path[:7] == "/caldav" {
  76. //CalDAV sub-router (bidirectional calendar sync for iOS)
  77. if CalDAVHandler == nil {
  78. errorHandleInternalServerError(w, r)
  79. return
  80. }
  81. CalDAVHandler.ServeHTTP(w, r)
  82. } else if r.URL.Path == "/.well-known/caldav" {
  83. //CalDAV service discovery redirect (RFC 6764)
  84. http.Redirect(w, r, "/caldav/", http.StatusMovedPermanently)
  85. } else if len(r.URL.Path) >= len("/webdav") && r.URL.Path[:7] == "/webdav" {
  86. //WebDAV sub-router
  87. if WebDAVManager == nil {
  88. errorHandleInternalServerError(w, r)
  89. return
  90. }
  91. WebDAVManager.HandleRequest(w, r)
  92. } else if len(r.URL.Path) >= len("/share") && r.URL.Path[:6] == "/share" {
  93. //Share Manager sub-router
  94. if shareManager == nil {
  95. errorHandleInternalServerError(w, r)
  96. return
  97. }
  98. shareManager.HandleShareAccess(w, r)
  99. } else if len(r.URL.Path) >= len("/api/remote") && r.URL.Path[:11] == "/api/remote" {
  100. //Serverless sub-router
  101. if AGIGateway == nil {
  102. errorHandleInternalServerError(w, r)
  103. return
  104. }
  105. AGIGateway.ExtAPIHandler(w, r)
  106. } else if len(r.URL.Path) >= len("/fileview") && r.URL.Path[:9] == "/fileview" {
  107. //File server sub-router
  108. if DirListManager == nil {
  109. errorHandleInternalServerError(w, r)
  110. return
  111. }
  112. DirListManager.ServerWebFileRequest(w, r)
  113. } else if r.URL.Path == "/" && authAgent.CheckAuth(r) {
  114. //Use logged in and request the index. Serve the user's interface module
  115. w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
  116. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  117. if err != nil {
  118. //ERROR!! Server default
  119. h.ServeHTTP(w, r)
  120. } else {
  121. interfaceModule := userinfo.GetInterfaceModules()
  122. if len(interfaceModule) == 1 && interfaceModule[0] == permission.SetupWizardModule && moduleHandler.GetModuleInfoByID(permission.SetupWizardModule) == nil {
  123. //The wizard was removed or switched off before it was finished: fall back to the desktop
  124. http.Redirect(w, r, "./desktop.html", http.StatusTemporaryRedirect)
  125. } else if len(interfaceModule) == 1 && interfaceModule[0] == "Desktop" {
  126. http.Redirect(w, r, "./desktop.html", http.StatusTemporaryRedirect)
  127. } else if len(interfaceModule) == 1 {
  128. //User with default interface module not desktop
  129. modileInfo := moduleHandler.GetModuleInfoByID(interfaceModule[0])
  130. if modileInfo == nil {
  131. //The module is not found or not enabled
  132. http.Redirect(w, r, "./SystemAO/boot/interface_disabled.html", http.StatusTemporaryRedirect)
  133. return
  134. }
  135. http.Redirect(w, r, modileInfo.StartDir, http.StatusTemporaryRedirect)
  136. } else if len(interfaceModule) > 1 {
  137. //Redirect to module selector
  138. http.Redirect(w, r, "./SystemAO/boot/interface_selector.html", http.StatusTemporaryRedirect)
  139. } else if len(interfaceModule) == 0 {
  140. //Redirect to error page
  141. http.Redirect(w, r, "./SystemAO/boot/no_interfaceing.html", http.StatusTemporaryRedirect)
  142. } else {
  143. //For unknown operations, send it to desktop
  144. http.Redirect(w, r, "./desktop.html", http.StatusTemporaryRedirect)
  145. }
  146. }
  147. } else if ((len(r.URL.Path) >= 5 && r.URL.Path[:5] == "/www/") || r.URL.Path == "/www") && *allow_homepage {
  148. //Serve the custom homepage of the user defined. Hand over to the www router
  149. userWwwHandler.RouteRequest(w, r)
  150. } else if authAgent.CheckAuth(r) {
  151. //User logged in. Continue to serve the file the client want
  152. authAgent.UpdateSessionExpireTime(w, r)
  153. if serveDisabledModuleFolder(w, r) {
  154. //The files of a WebApp an admin switched off are not served
  155. return
  156. }
  157. if localeServer != nil && strings.HasPrefix(r.URL.Path, locale.URLPrefix) {
  158. //System locale files live in ./system/locale, rendered per user (locale.fonts.go)
  159. serveLocaleRequest(w, r)
  160. return
  161. }
  162. if build_version == "development" {
  163. //Do something if development build
  164. //w.Header().Add("Cross-Origin-Opener-Policy", "same-origin")
  165. //w.Header().Add("Cross-Origin-Embedder-Policy", "require-corp")
  166. }
  167. if filepath.Ext("web"+fs.DecodeURI(r.RequestURI)) == ".js" {
  168. //Fixed serve js meme type invalid bug on Firefox
  169. w.Header().Add("Content-Type", "application/javascript; charset=UTF-8")
  170. }
  171. if !*disable_subservices {
  172. //Enable subservice access
  173. //Check if this path is reverse proxy path. If yes, serve with proxyserver
  174. isRP, proxy, rewriteURL, subserviceObject := ssRouter.CheckIfReverseProxyPath(r)
  175. if isRP {
  176. //Check user permission on that module
  177. ssRouter.HandleRoutingRequest(w, r, proxy, subserviceObject, rewriteURL)
  178. return
  179. }
  180. }
  181. //Not subservice routine. Handle file server
  182. if !*enable_dir_listing {
  183. if strings.HasSuffix(r.URL.Path, "/") {
  184. //User trying to access a directory. Send NOT FOUND.
  185. if fileExistsInWebOrVendor(r.URL.Path + "index.html") {
  186. //Index exists. Allow passthrough
  187. } else {
  188. errorHandleNotFound(w, r)
  189. return
  190. }
  191. }
  192. }
  193. if !fileExistsInWebOrVendor(r.URL.Path) {
  194. //File not found
  195. errorHandleNotFound(w, r)
  196. return
  197. }
  198. routerStaticContentServer(h, w, r)
  199. } else {
  200. //User not logged in. Check if the path end with public/. If yes, allow public access
  201. if !fileExistsInWebOrVendor(r.URL.Path) {
  202. //Requested file not exists on the server. Return not found
  203. errorHandleNotFound(w, r)
  204. } else if r.URL.Path[len(r.URL.Path)-1:] != "/" && filepath.Base(filepath.Dir(r.URL.Path)) == "public" {
  205. //This file path end with public/. Allow public access
  206. routerStaticContentServer(h, w, r)
  207. } else if *allow_homepage && len(r.URL.Path) >= 5 && r.URL.Path[:5] == "/www/" {
  208. //Handle public home serving if homepage mode is enabled
  209. routerStaticContentServer(h, w, r)
  210. } else {
  211. //Other paths
  212. //Rediect to login page
  213. w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
  214. http.Redirect(w, r, utils.ConstructRelativePathFromRequestURL(r.RequestURI, "login.html")+"?redirect="+r.URL.String(), 307)
  215. }
  216. }
  217. })
  218. }
  219. // fileExistsInWebOrVendor reports whether a URL path resolves to a file in
  220. // either the standard ./web directory or the vendorResRoot/web/ overlay.
  221. func fileExistsInWebOrVendor(urlPath string) bool {
  222. if fs.FileExists("web" + urlPath) {
  223. return true
  224. }
  225. return fs.FileExists(filepath.Join(vendorResRoot, "web", urlPath))
  226. }
  227. func routerStaticContentServer(h http.Handler, w http.ResponseWriter, r *http.Request) {
  228. if *enable_gzip {
  229. gzipmiddleware.Compress(h).ServeHTTP(w, r)
  230. } else {
  231. h.ServeHTTP(w, r)
  232. }
  233. }
  234. // serveDisabledModuleFolder answers a request for a file of a WebApp whose
  235. // modules are all disabled, and reports whether it did. The Setup module goes
  236. // back to the startup interface once it is finished, other apps are not found.
  237. // Images stay reachable, so the module manager can still show the app's icon.
  238. func serveDisabledModuleFolder(w http.ResponseWriter, r *http.Request) bool {
  239. if moduleHandler == nil {
  240. return false
  241. }
  242. folder := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
  243. if folder == "" || !moduleHandler.IsSourceFolderDisabled("web/"+folder) {
  244. return false
  245. }
  246. switch strings.ToLower(filepath.Ext(r.URL.Path)) {
  247. case ".png", ".svg", ".jpg", ".jpeg", ".gif", ".webp", ".ico":
  248. return false
  249. }
  250. if strings.EqualFold(folder, setupWizardFolder) {
  251. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  252. return true
  253. }
  254. errorHandleNotFound(w, r)
  255. return true
  256. }