main.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "path/filepath"
  9. "strconv"
  10. "syscall"
  11. "time"
  12. console "imuslab.com/arozos/mod/console"
  13. fs "imuslab.com/arozos/mod/filesystem"
  14. "imuslab.com/arozos/mod/info/logger"
  15. )
  16. /*
  17. arozos
  18. author: tobychui
  19. To edit startup flags, see main.flag.go
  20. To edit main routing logic, see main.router.go
  21. To edit startup sequence, see startup.go
  22. P.S. Try to keep this file < 300 lines
  23. */
  24. // Close handler, close db and clearn up everything before exit
  25. func SetupCloseHandler() {
  26. c := make(chan os.Signal, 2)
  27. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  28. go func() {
  29. <-c
  30. executeShutdownSequence()
  31. }()
  32. }
  33. func executeShutdownSequence() {
  34. //Shutdown cluster agent so peers stop routing to this node
  35. systemWideLogger.PrintAndLog("System", "<!> Shutting down cluster agent", nil)
  36. ClusterShutdown()
  37. //Shutdown the SMB server before the drives it serves
  38. SMBServerShutdown()
  39. //Shutdown authAgent
  40. systemWideLogger.PrintAndLog("System", "<!> Shutting down auth gateway", nil)
  41. authAgent.Close()
  42. //Shutdown the mail backend (outbox, IMAP connections, mail database)
  43. if mailBackend != nil {
  44. systemWideLogger.PrintAndLog("System", "<!> Shutting down mail backend", nil)
  45. mailBackend.Close()
  46. }
  47. //Shutdown all storage pools
  48. systemWideLogger.PrintAndLog("System", "<!> Shutting down storage pools", nil)
  49. closeAllStoragePools()
  50. //Shutdown Logger
  51. systemWideLogger.Close()
  52. //Shutdown database
  53. systemWideLogger.PrintAndLog("System", "<!> Shutting down database", nil)
  54. sysdb.Close()
  55. //Shutdown network services
  56. StopNetworkServices()
  57. //Shutdown Arozcast TURN relay
  58. if arozcastTurnRunning() {
  59. systemWideLogger.PrintAndLog("System", "<!> Shutting down Arozcast TURN relay", nil)
  60. arozcastStopTurnRelay()
  61. }
  62. //Shutdown FTP and SFTP Servers, keeping whether they start on boot
  63. if FTPManager != nil {
  64. systemWideLogger.PrintAndLog("System", "<!> Shutting down FTP Server", nil)
  65. FTPManager.Close()
  66. }
  67. if SFTPManager != nil {
  68. SFTPManager.Close()
  69. }
  70. //Shutdown media server, stopping any running HLS transcode
  71. if mediaServer != nil {
  72. systemWideLogger.PrintAndLog("System", "<!> Shutting down media server", nil)
  73. mediaServer.Close()
  74. }
  75. //Cleaning up tmp files
  76. systemWideLogger.PrintAndLog("System", "<!> Cleaning up tmp folder", nil)
  77. os.RemoveAll(*tmp_directory)
  78. //Do other things
  79. os.Exit(0)
  80. }
  81. func main() {
  82. //Parse startup flags and paramters
  83. flag.Parse()
  84. logger.SetGlobalJSONOutput(*log_format == "json")
  85. //Handle version printing
  86. if *show_version {
  87. fmt.Println("ArozOS " + build_version + " Revision " + internal_version)
  88. fmt.Println("Developed by tobychui and other co-developers, Licensed to " + deviceVendor)
  89. //fmt.Println("THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.")
  90. os.Exit(0)
  91. }
  92. //Handle flag assignments
  93. max_upload_size = int64(*max_upload) << 20 //Parse the max upload size
  94. //Clean up previous tmp files
  95. final_tmp_directory := filepath.Clean(*tmp_directory) + "/tmp/"
  96. tmp_directory = &final_tmp_directory
  97. os.RemoveAll(*tmp_directory)
  98. os.Mkdir(*tmp_directory, 0777)
  99. // Initialize a temporary stdout-only logger so calls before RunStartup are safe.
  100. // RunStartup will replace this with a file-backed logger.
  101. systemWideLogger, _ = logger.NewTmpLogger()
  102. logger.SetDefaultLogger(systemWideLogger)
  103. //Print copyRight information
  104. systemWideLogger.PrintAndLog("System", "ArozOS(C) "+strconv.Itoa(time.Now().Year())+" "+deviceVendor+".", nil)
  105. systemWideLogger.PrintAndLog("System", "ArozOS "+build_version+" Revision "+internal_version, nil)
  106. /*
  107. New Implementation of the ArOZ Online System, Sept 2020
  108. */
  109. RunStartup()
  110. /*
  111. Development build test execution
  112. */
  113. Run_Test()
  114. //Initiate all the static files transfer
  115. baseFileServer := http.FileServer(http.Dir("./web"))
  116. vendorWebDir := filepath.Join(vendorResRoot, "web")
  117. // Wrap the base file server: serve from vendorResRoot/web/ when a matching
  118. // file exists there, falling through to ./web/ otherwise.
  119. fileServer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  120. vendorPath := filepath.Join(vendorWebDir, filepath.FromSlash(r.URL.Path))
  121. if !vendorWebExists {
  122. // Early exit if the vendor web directory doesn't exist, to avoid unnecessary file existence checks on every request.
  123. baseFileServer.ServeHTTP(w, r)
  124. return
  125. }
  126. if info, err := os.Stat(vendorPath); err == nil && !info.IsDir() {
  127. http.ServeFile(w, r, vendorPath)
  128. return
  129. }
  130. baseFileServer.ServeHTTP(w, r)
  131. })
  132. vendorWebExists = fs.FileExists(vendorWebDir)
  133. //Updates 2022-09-06: Gzip handler moved inside the master router
  134. http.Handle("/", mrouter(fileServer))
  135. //Setup handler for Ctrl +C
  136. SetupCloseHandler()
  137. //Start http server
  138. go func() {
  139. if *use_tls {
  140. if !*disable_http {
  141. go func() {
  142. address := fmt.Sprintf("%s:%d", *listen_host, *listen_port)
  143. systemWideLogger.PrintAndLog("System", fmt.Sprint("Standard (HTTP) Web server listening at", address), nil)
  144. http.ListenAndServe(address, nil)
  145. }()
  146. }
  147. address := fmt.Sprintf("%s:%d", *listen_host, *tls_listen_port)
  148. systemWideLogger.PrintAndLog("System", fmt.Sprint("Secure (HTTPS) Web server listening at", address), nil)
  149. http.ListenAndServeTLS(address, *tls_cert, *tls_key, nil)
  150. } else {
  151. address := fmt.Sprintf("%s:%d", *listen_host, *listen_port)
  152. systemWideLogger.PrintAndLog("System", fmt.Sprint("Web server listening at", address), nil)
  153. http.ListenAndServe(address, nil)
  154. }
  155. }()
  156. if *enable_console {
  157. //Startup interactive shell for debug and basic controls
  158. Console := console.NewConsole(consoleCommandHandler)
  159. Console.ListenAndHandle()
  160. } else {
  161. //Just do a blocking loop here
  162. select {}
  163. }
  164. }