main.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. SyncthingShutdown() //Syncthing writes into the drives too
  40. //Shutdown authAgent
  41. systemWideLogger.PrintAndLog("System", "<!> Shutting down auth gateway", nil)
  42. authAgent.Close()
  43. //Shutdown the mail backend (outbox, IMAP connections, mail database)
  44. if mailBackend != nil {
  45. systemWideLogger.PrintAndLog("System", "<!> Shutting down mail backend", nil)
  46. mailBackend.Close()
  47. }
  48. //Shutdown all storage pools
  49. systemWideLogger.PrintAndLog("System", "<!> Shutting down storage pools", nil)
  50. closeAllStoragePools()
  51. //Shutdown Logger
  52. systemWideLogger.Close()
  53. //Shutdown database
  54. systemWideLogger.PrintAndLog("System", "<!> Shutting down database", nil)
  55. sysdb.Close()
  56. //Shutdown network services
  57. StopNetworkServices()
  58. //Shutdown Arozcast TURN relay
  59. if arozcastTurnRunning() {
  60. systemWideLogger.PrintAndLog("System", "<!> Shutting down Arozcast TURN relay", nil)
  61. arozcastStopTurnRelay()
  62. }
  63. //Shutdown FTP and SFTP Servers, keeping whether they start on boot
  64. if FTPManager != nil {
  65. systemWideLogger.PrintAndLog("System", "<!> Shutting down FTP Server", nil)
  66. FTPManager.Close()
  67. }
  68. if SFTPManager != nil {
  69. SFTPManager.Close()
  70. }
  71. //Shutdown media server, stopping any running HLS transcode
  72. if mediaServer != nil {
  73. systemWideLogger.PrintAndLog("System", "<!> Shutting down media server", nil)
  74. mediaServer.Close()
  75. }
  76. //Cleaning up tmp files
  77. systemWideLogger.PrintAndLog("System", "<!> Cleaning up tmp folder", nil)
  78. os.RemoveAll(*tmp_directory)
  79. //Do other things
  80. os.Exit(0)
  81. }
  82. func main() {
  83. //Parse startup flags and paramters
  84. flag.Parse()
  85. logger.SetGlobalJSONOutput(*log_format == "json")
  86. //Handle version printing
  87. if *show_version {
  88. fmt.Println("ArozOS " + build_version + " Revision " + internal_version)
  89. fmt.Println("Developed by tobychui and other co-developers, Licensed to " + deviceVendor)
  90. //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.")
  91. os.Exit(0)
  92. }
  93. //Handle flag assignments
  94. max_upload_size = int64(*max_upload) << 20 //Parse the max upload size
  95. //Clean up previous tmp files
  96. final_tmp_directory := filepath.Clean(*tmp_directory) + "/tmp/"
  97. tmp_directory = &final_tmp_directory
  98. os.RemoveAll(*tmp_directory)
  99. os.Mkdir(*tmp_directory, 0777)
  100. // Initialize a temporary stdout-only logger so calls before RunStartup are safe.
  101. // RunStartup will replace this with a file-backed logger.
  102. systemWideLogger, _ = logger.NewTmpLogger()
  103. logger.SetDefaultLogger(systemWideLogger)
  104. //Print copyRight information
  105. systemWideLogger.PrintAndLog("System", "ArozOS(C) "+strconv.Itoa(time.Now().Year())+" "+deviceVendor+".", nil)
  106. systemWideLogger.PrintAndLog("System", "ArozOS "+build_version+" Revision "+internal_version, nil)
  107. /*
  108. New Implementation of the ArOZ Online System, Sept 2020
  109. */
  110. RunStartup()
  111. /*
  112. Development build test execution
  113. */
  114. Run_Test()
  115. //Initiate all the static files transfer
  116. baseFileServer := http.FileServer(http.Dir("./web"))
  117. vendorWebDir := filepath.Join(vendorResRoot, "web")
  118. // Wrap the base file server: serve from vendorResRoot/web/ when a matching
  119. // file exists there, falling through to ./web/ otherwise.
  120. fileServer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  121. vendorPath := filepath.Join(vendorWebDir, filepath.FromSlash(r.URL.Path))
  122. if !vendorWebExists {
  123. // Early exit if the vendor web directory doesn't exist, to avoid unnecessary file existence checks on every request.
  124. baseFileServer.ServeHTTP(w, r)
  125. return
  126. }
  127. if info, err := os.Stat(vendorPath); err == nil && !info.IsDir() {
  128. http.ServeFile(w, r, vendorPath)
  129. return
  130. }
  131. baseFileServer.ServeHTTP(w, r)
  132. })
  133. vendorWebExists = fs.FileExists(vendorWebDir)
  134. //Updates 2022-09-06: Gzip handler moved inside the master router
  135. http.Handle("/", mrouter(fileServer))
  136. //Setup handler for Ctrl +C
  137. SetupCloseHandler()
  138. //Start http server
  139. go func() {
  140. if *use_tls {
  141. if !*disable_http {
  142. go func() {
  143. address := fmt.Sprintf("%s:%d", *listen_host, *listen_port)
  144. systemWideLogger.PrintAndLog("System", fmt.Sprint("Standard (HTTP) Web server listening at", address), nil)
  145. http.ListenAndServe(address, nil)
  146. }()
  147. }
  148. address := fmt.Sprintf("%s:%d", *listen_host, *tls_listen_port)
  149. systemWideLogger.PrintAndLog("System", fmt.Sprint("Secure (HTTPS) Web server listening at", address), nil)
  150. http.ListenAndServeTLS(address, *tls_cert, *tls_key, nil)
  151. } else {
  152. address := fmt.Sprintf("%s:%d", *listen_host, *listen_port)
  153. systemWideLogger.PrintAndLog("System", fmt.Sprint("Web server listening at", address), nil)
  154. http.ListenAndServe(address, nil)
  155. }
  156. }()
  157. if *enable_console {
  158. //Startup interactive shell for debug and basic controls
  159. Console := console.NewConsole(consoleCommandHandler)
  160. Console.ListenAndHandle()
  161. } else {
  162. //Just do a blocking loop here
  163. select {}
  164. }
  165. }