install.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package route
  5. import (
  6. "net/mail"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "github.com/unknwon/com"
  12. "gopkg.in/ini.v1"
  13. "gopkg.in/macaron.v1"
  14. log "unknwon.dev/clog/v2"
  15. "xorm.io/xorm"
  16. "github.com/gogs/git-module"
  17. "gogs.io/gogs/internal/context"
  18. "gogs.io/gogs/internal/cron"
  19. "gogs.io/gogs/internal/db"
  20. "gogs.io/gogs/internal/form"
  21. "gogs.io/gogs/internal/mailer"
  22. "gogs.io/gogs/internal/markup"
  23. "gogs.io/gogs/internal/setting"
  24. "gogs.io/gogs/internal/ssh"
  25. "gogs.io/gogs/internal/template/highlight"
  26. "gogs.io/gogs/internal/tool"
  27. "gogs.io/gogs/internal/user"
  28. )
  29. const (
  30. INSTALL = "install"
  31. )
  32. func checkRunMode() {
  33. if setting.ProdMode {
  34. macaron.Env = macaron.PROD
  35. macaron.ColorLog = false
  36. } else {
  37. git.Debug = true
  38. }
  39. log.Info("Run mode: %s", strings.Title(macaron.Env))
  40. }
  41. // GlobalInit is for global configuration reload-able.
  42. func GlobalInit() {
  43. setting.Init()
  44. setting.InitLogging()
  45. log.Info("%s %s", setting.AppName, setting.AppVersion)
  46. log.Trace("Custom path: %s", setting.CustomPath)
  47. log.Trace("Log path: %s", setting.LogRootPath)
  48. log.Trace("Build time: %s", setting.BuildTime)
  49. log.Trace("Build commit: %s", setting.BuildCommit)
  50. db.LoadConfigs()
  51. setting.NewServices()
  52. mailer.NewContext()
  53. if setting.InstallLock {
  54. highlight.NewContext()
  55. markup.NewSanitizer()
  56. if err := db.NewEngine(); err != nil {
  57. log.Fatal("Failed to initialize ORM engine: %v", err)
  58. }
  59. db.HasEngine = true
  60. db.LoadAuthSources()
  61. db.LoadRepoConfig()
  62. db.NewRepoContext()
  63. // Booting long running goroutines.
  64. cron.NewContext()
  65. db.InitSyncMirrors()
  66. db.InitDeliverHooks()
  67. db.InitTestPullRequests()
  68. }
  69. if db.EnableSQLite3 {
  70. log.Info("SQLite3 is supported")
  71. }
  72. if setting.SupportWindowsService() {
  73. log.Info("Builtin Windows Service is supported")
  74. }
  75. if setting.LoadAssetsFromDisk {
  76. log.Trace("Assets are loaded from disk")
  77. }
  78. checkRunMode()
  79. if !setting.InstallLock {
  80. return
  81. }
  82. if setting.SSH.StartBuiltinServer {
  83. ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers)
  84. log.Info("SSH server started on %s:%v", setting.SSH.ListenHost, setting.SSH.ListenPort)
  85. log.Trace("SSH server cipher list: %v", setting.SSH.ServerCiphers)
  86. }
  87. if setting.SSH.RewriteAuthorizedKeysAtStart {
  88. if err := db.RewriteAuthorizedKeys(); err != nil {
  89. log.Warn("Failed to rewrite authorized_keys file: %v", err)
  90. }
  91. }
  92. }
  93. func InstallInit(c *context.Context) {
  94. if setting.InstallLock {
  95. c.NotFound()
  96. return
  97. }
  98. c.Title("install.install")
  99. c.PageIs("Install")
  100. dbOpts := []string{"MySQL", "PostgreSQL", "MSSQL"}
  101. if db.EnableSQLite3 {
  102. dbOpts = append(dbOpts, "SQLite3")
  103. }
  104. c.Data["DbOptions"] = dbOpts
  105. }
  106. func Install(c *context.Context) {
  107. f := form.Install{}
  108. // Database settings
  109. f.DbHost = db.DbCfg.Host
  110. f.DbUser = db.DbCfg.User
  111. f.DbName = db.DbCfg.Name
  112. f.DbPath = db.DbCfg.Path
  113. c.Data["CurDbOption"] = "MySQL"
  114. switch db.DbCfg.Type {
  115. case "postgres":
  116. c.Data["CurDbOption"] = "PostgreSQL"
  117. case "mssql":
  118. c.Data["CurDbOption"] = "MSSQL"
  119. case "sqlite3":
  120. if db.EnableSQLite3 {
  121. c.Data["CurDbOption"] = "SQLite3"
  122. }
  123. }
  124. // Application general settings
  125. f.AppName = setting.AppName
  126. f.RepoRootPath = setting.RepoRootPath
  127. // Note(unknwon): it's hard for Windows users change a running user,
  128. // so just use current one if config says default.
  129. if setting.IsWindows && setting.RunUser == "git" {
  130. f.RunUser = user.CurrentUsername()
  131. } else {
  132. f.RunUser = setting.RunUser
  133. }
  134. f.Domain = setting.Domain
  135. f.SSHPort = setting.SSH.Port
  136. f.UseBuiltinSSHServer = setting.SSH.StartBuiltinServer
  137. f.HTTPPort = setting.HTTPPort
  138. f.AppUrl = setting.AppURL
  139. f.LogRootPath = setting.LogRootPath
  140. // E-mail service settings
  141. if setting.MailService != nil {
  142. f.SMTPHost = setting.MailService.Host
  143. f.SMTPFrom = setting.MailService.From
  144. f.SMTPUser = setting.MailService.User
  145. }
  146. f.RegisterConfirm = setting.Service.RegisterEmailConfirm
  147. f.MailNotify = setting.Service.EnableNotifyMail
  148. // Server and other services settings
  149. f.OfflineMode = setting.OfflineMode
  150. f.DisableGravatar = setting.DisableGravatar
  151. f.EnableFederatedAvatar = setting.EnableFederatedAvatar
  152. f.DisableRegistration = setting.Service.DisableRegistration
  153. f.EnableCaptcha = setting.Service.EnableCaptcha
  154. f.RequireSignInView = setting.Service.RequireSignInView
  155. form.Assign(f, c.Data)
  156. c.Success(INSTALL)
  157. }
  158. func InstallPost(c *context.Context, f form.Install) {
  159. c.Data["CurDbOption"] = f.DbType
  160. if c.HasError() {
  161. if c.HasValue("Err_SMTPEmail") {
  162. c.FormErr("SMTP")
  163. }
  164. if c.HasValue("Err_AdminName") ||
  165. c.HasValue("Err_AdminPasswd") ||
  166. c.HasValue("Err_AdminEmail") {
  167. c.FormErr("Admin")
  168. }
  169. c.Success(INSTALL)
  170. return
  171. }
  172. if _, err := exec.LookPath("git"); err != nil {
  173. c.RenderWithErr(c.Tr("install.test_git_failed", err), INSTALL, &f)
  174. return
  175. }
  176. // Pass basic check, now test configuration.
  177. // Test database setting.
  178. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"}
  179. db.DbCfg.Type = dbTypes[f.DbType]
  180. db.DbCfg.Host = f.DbHost
  181. db.DbCfg.User = f.DbUser
  182. db.DbCfg.Passwd = f.DbPasswd
  183. db.DbCfg.Name = f.DbName
  184. db.DbCfg.SSLMode = f.SSLMode
  185. db.DbCfg.Path = f.DbPath
  186. if db.DbCfg.Type == "sqlite3" && len(db.DbCfg.Path) == 0 {
  187. c.FormErr("DbPath")
  188. c.RenderWithErr(c.Tr("install.err_empty_db_path"), INSTALL, &f)
  189. return
  190. }
  191. // Set test engine.
  192. var x *xorm.Engine
  193. if err := db.NewTestEngine(x); err != nil {
  194. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  195. c.FormErr("DbType")
  196. c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
  197. } else {
  198. c.FormErr("DbSetting")
  199. c.RenderWithErr(c.Tr("install.invalid_db_setting", err), INSTALL, &f)
  200. }
  201. return
  202. }
  203. // Test repository root path.
  204. f.RepoRootPath = strings.Replace(f.RepoRootPath, "\\", "/", -1)
  205. if err := os.MkdirAll(f.RepoRootPath, os.ModePerm); err != nil {
  206. c.FormErr("RepoRootPath")
  207. c.RenderWithErr(c.Tr("install.invalid_repo_path", err), INSTALL, &f)
  208. return
  209. }
  210. // Test log root path.
  211. f.LogRootPath = strings.Replace(f.LogRootPath, "\\", "/", -1)
  212. if err := os.MkdirAll(f.LogRootPath, os.ModePerm); err != nil {
  213. c.FormErr("LogRootPath")
  214. c.RenderWithErr(c.Tr("install.invalid_log_root_path", err), INSTALL, &f)
  215. return
  216. }
  217. currentUser, match := setting.IsRunUserMatchCurrentUser(f.RunUser)
  218. if !match {
  219. c.FormErr("RunUser")
  220. c.RenderWithErr(c.Tr("install.run_user_not_match", f.RunUser, currentUser), INSTALL, &f)
  221. return
  222. }
  223. // Check host address and port
  224. if len(f.SMTPHost) > 0 && !strings.Contains(f.SMTPHost, ":") {
  225. c.FormErr("SMTP", "SMTPHost")
  226. c.RenderWithErr(c.Tr("install.smtp_host_missing_port"), INSTALL, &f)
  227. return
  228. }
  229. // Make sure FROM field is valid
  230. if len(f.SMTPFrom) > 0 {
  231. _, err := mail.ParseAddress(f.SMTPFrom)
  232. if err != nil {
  233. c.FormErr("SMTP", "SMTPFrom")
  234. c.RenderWithErr(c.Tr("install.invalid_smtp_from", err), INSTALL, &f)
  235. return
  236. }
  237. }
  238. // Check logic loophole between disable self-registration and no admin account.
  239. if f.DisableRegistration && len(f.AdminName) == 0 {
  240. c.FormErr("Services", "Admin")
  241. c.RenderWithErr(c.Tr("install.no_admin_and_disable_registration"), INSTALL, f)
  242. return
  243. }
  244. // Check admin password.
  245. if len(f.AdminName) > 0 && len(f.AdminPasswd) == 0 {
  246. c.FormErr("Admin", "AdminPasswd")
  247. c.RenderWithErr(c.Tr("install.err_empty_admin_password"), INSTALL, f)
  248. return
  249. }
  250. if f.AdminPasswd != f.AdminConfirmPasswd {
  251. c.FormErr("Admin", "AdminPasswd")
  252. c.RenderWithErr(c.Tr("form.password_not_match"), INSTALL, f)
  253. return
  254. }
  255. if f.AppUrl[len(f.AppUrl)-1] != '/' {
  256. f.AppUrl += "/"
  257. }
  258. // Save settings.
  259. cfg := ini.Empty()
  260. if com.IsFile(setting.CustomConf) {
  261. // Keeps custom settings if there is already something.
  262. if err := cfg.Append(setting.CustomConf); err != nil {
  263. log.Error("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  264. }
  265. }
  266. cfg.Section("database").Key("DB_TYPE").SetValue(db.DbCfg.Type)
  267. cfg.Section("database").Key("HOST").SetValue(db.DbCfg.Host)
  268. cfg.Section("database").Key("NAME").SetValue(db.DbCfg.Name)
  269. cfg.Section("database").Key("USER").SetValue(db.DbCfg.User)
  270. cfg.Section("database").Key("PASSWD").SetValue(db.DbCfg.Passwd)
  271. cfg.Section("database").Key("SSL_MODE").SetValue(db.DbCfg.SSLMode)
  272. cfg.Section("database").Key("PATH").SetValue(db.DbCfg.Path)
  273. cfg.Section("").Key("APP_NAME").SetValue(f.AppName)
  274. cfg.Section("repository").Key("ROOT").SetValue(f.RepoRootPath)
  275. cfg.Section("").Key("RUN_USER").SetValue(f.RunUser)
  276. cfg.Section("server").Key("DOMAIN").SetValue(f.Domain)
  277. cfg.Section("server").Key("HTTP_PORT").SetValue(f.HTTPPort)
  278. cfg.Section("server").Key("ROOT_URL").SetValue(f.AppUrl)
  279. if f.SSHPort == 0 {
  280. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  281. } else {
  282. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  283. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(f.SSHPort))
  284. cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(f.UseBuiltinSSHServer))
  285. }
  286. if len(strings.TrimSpace(f.SMTPHost)) > 0 {
  287. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  288. cfg.Section("mailer").Key("HOST").SetValue(f.SMTPHost)
  289. cfg.Section("mailer").Key("FROM").SetValue(f.SMTPFrom)
  290. cfg.Section("mailer").Key("USER").SetValue(f.SMTPUser)
  291. cfg.Section("mailer").Key("PASSWD").SetValue(f.SMTPPasswd)
  292. } else {
  293. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  294. }
  295. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(f.RegisterConfirm))
  296. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(f.MailNotify))
  297. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(f.OfflineMode))
  298. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(f.DisableGravatar))
  299. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(f.EnableFederatedAvatar))
  300. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(f.DisableRegistration))
  301. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(f.EnableCaptcha))
  302. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(f.RequireSignInView))
  303. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  304. cfg.Section("session").Key("PROVIDER").SetValue("file")
  305. mode := "file"
  306. if f.EnableConsoleMode {
  307. mode = "console, file"
  308. }
  309. cfg.Section("log").Key("MODE").SetValue(mode)
  310. cfg.Section("log").Key("LEVEL").SetValue("Info")
  311. cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath)
  312. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  313. secretKey, err := tool.RandomString(15)
  314. if err != nil {
  315. c.RenderWithErr(c.Tr("install.secret_key_failed", err), INSTALL, &f)
  316. return
  317. }
  318. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  319. os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  320. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  321. c.RenderWithErr(c.Tr("install.save_config_failed", err), INSTALL, &f)
  322. return
  323. }
  324. GlobalInit()
  325. // Create admin account
  326. if len(f.AdminName) > 0 {
  327. u := &db.User{
  328. Name: f.AdminName,
  329. Email: f.AdminEmail,
  330. Passwd: f.AdminPasswd,
  331. IsAdmin: true,
  332. IsActive: true,
  333. }
  334. if err := db.CreateUser(u); err != nil {
  335. if !db.IsErrUserAlreadyExist(err) {
  336. setting.InstallLock = false
  337. c.FormErr("AdminName", "AdminEmail")
  338. c.RenderWithErr(c.Tr("install.invalid_admin_setting", err), INSTALL, &f)
  339. return
  340. }
  341. log.Info("Admin account already exist")
  342. u, _ = db.GetUserByName(u.Name)
  343. }
  344. // Auto-login for admin
  345. c.Session.Set("uid", u.ID)
  346. c.Session.Set("uname", u.Name)
  347. }
  348. log.Info("First-time run install finished!")
  349. c.Flash.Success(c.Tr("install.install_success"))
  350. c.Redirect(f.AppUrl + "user/login")
  351. }