main.router.go 9.3 KB

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