install.go 12 KB

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