You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

install.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 routers
  5. import (
  6. "errors"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/generate"
  16. "code.gitea.io/gitea/modules/graceful"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/user"
  20. "github.com/unknwon/com"
  21. "gopkg.in/ini.v1"
  22. "xorm.io/xorm"
  23. )
  24. const (
  25. // tplInstall template for installation page
  26. tplInstall base.TplName = "install"
  27. )
  28. // InstallInit prepare for rendering installation page
  29. func InstallInit(ctx *context.Context) {
  30. if setting.InstallLock {
  31. ctx.NotFound("Install", errors.New("Installation is prohibited"))
  32. return
  33. }
  34. ctx.Data["Title"] = ctx.Tr("install.install")
  35. ctx.Data["PageIsInstall"] = true
  36. ctx.Data["DbOptions"] = setting.SupportedDatabases
  37. }
  38. // Install render installation page
  39. func Install(ctx *context.Context) {
  40. form := auth.InstallForm{}
  41. // Database settings
  42. form.DbHost = setting.Database.Host
  43. form.DbUser = setting.Database.User
  44. form.DbPasswd = setting.Database.Passwd
  45. form.DbName = setting.Database.Name
  46. form.DbPath = setting.Database.Path
  47. form.Charset = setting.Database.Charset
  48. ctx.Data["CurDbOption"] = "MySQL"
  49. switch setting.Database.Type {
  50. case "postgres":
  51. ctx.Data["CurDbOption"] = "PostgreSQL"
  52. case "mssql":
  53. ctx.Data["CurDbOption"] = "MSSQL"
  54. case "sqlite3":
  55. if setting.EnableSQLite3 {
  56. ctx.Data["CurDbOption"] = "SQLite3"
  57. }
  58. }
  59. // Application general settings
  60. form.AppName = setting.AppName
  61. form.RepoRootPath = setting.RepoRootPath
  62. form.LFSRootPath = setting.LFS.ContentPath
  63. // Note(unknown): it's hard for Windows users change a running user,
  64. // so just use current one if config says default.
  65. if setting.IsWindows && setting.RunUser == "git" {
  66. form.RunUser = user.CurrentUsername()
  67. } else {
  68. form.RunUser = setting.RunUser
  69. }
  70. form.Domain = setting.Domain
  71. form.SSHPort = setting.SSH.Port
  72. form.HTTPPort = setting.HTTPPort
  73. form.AppURL = setting.AppURL
  74. form.LogRootPath = setting.LogRootPath
  75. // E-mail service settings
  76. if setting.MailService != nil {
  77. form.SMTPHost = setting.MailService.Host
  78. form.SMTPFrom = setting.MailService.From
  79. form.SMTPUser = setting.MailService.User
  80. }
  81. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  82. form.MailNotify = setting.Service.EnableNotifyMail
  83. // Server and other services settings
  84. form.OfflineMode = setting.OfflineMode
  85. form.DisableGravatar = setting.DisableGravatar
  86. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  87. form.EnableOpenIDSignIn = setting.Service.EnableOpenIDSignIn
  88. form.EnableOpenIDSignUp = setting.Service.EnableOpenIDSignUp
  89. form.DisableRegistration = setting.Service.DisableRegistration
  90. form.AllowOnlyExternalRegistration = setting.Service.AllowOnlyExternalRegistration
  91. form.EnableCaptcha = setting.Service.EnableCaptcha
  92. form.RequireSignInView = setting.Service.RequireSignInView
  93. form.DefaultKeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  94. form.DefaultAllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  95. form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
  96. form.NoReplyAddress = setting.Service.NoReplyAddress
  97. auth.AssignForm(form, ctx.Data)
  98. ctx.HTML(200, tplInstall)
  99. }
  100. // InstallPost response for submit install items
  101. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  102. var err error
  103. ctx.Data["CurDbOption"] = form.DbType
  104. if ctx.HasError() {
  105. if ctx.HasValue("Err_SMTPUser") {
  106. ctx.Data["Err_SMTP"] = true
  107. }
  108. if ctx.HasValue("Err_AdminName") ||
  109. ctx.HasValue("Err_AdminPasswd") ||
  110. ctx.HasValue("Err_AdminEmail") {
  111. ctx.Data["Err_Admin"] = true
  112. }
  113. ctx.HTML(200, tplInstall)
  114. return
  115. }
  116. if _, err = exec.LookPath("git"); err != nil {
  117. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form)
  118. return
  119. }
  120. // Pass basic check, now test configuration.
  121. // Test database setting.
  122. setting.Database.Type = setting.GetDBTypeByName(form.DbType)
  123. setting.Database.Host = form.DbHost
  124. setting.Database.User = form.DbUser
  125. setting.Database.Passwd = form.DbPasswd
  126. setting.Database.Name = form.DbName
  127. setting.Database.SSLMode = form.SSLMode
  128. setting.Database.Charset = form.Charset
  129. setting.Database.Path = form.DbPath
  130. if (setting.Database.Type == "sqlite3") &&
  131. len(setting.Database.Path) == 0 {
  132. ctx.Data["Err_DbPath"] = true
  133. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form)
  134. return
  135. }
  136. // Set test engine.
  137. var x *xorm.Engine
  138. if err = models.NewTestEngine(x); err != nil {
  139. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  140. ctx.Data["Err_DbType"] = true
  141. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/en-us/install-from-binary/"), tplInstall, &form)
  142. } else {
  143. ctx.Data["Err_DbSetting"] = true
  144. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form)
  145. }
  146. return
  147. }
  148. // Test repository root path.
  149. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  150. if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  151. ctx.Data["Err_RepoRootPath"] = true
  152. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
  153. return
  154. }
  155. // Test LFS root path if not empty, empty meaning disable LFS
  156. if form.LFSRootPath != "" {
  157. form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
  158. if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
  159. ctx.Data["Err_LFSRootPath"] = true
  160. ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
  161. return
  162. }
  163. }
  164. // Test log root path.
  165. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  166. if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  167. ctx.Data["Err_LogRootPath"] = true
  168. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
  169. return
  170. }
  171. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  172. if !match {
  173. ctx.Data["Err_RunUser"] = true
  174. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form)
  175. return
  176. }
  177. // Check logic loophole between disable self-registration and no admin account.
  178. if form.DisableRegistration && len(form.AdminName) == 0 {
  179. ctx.Data["Err_Services"] = true
  180. ctx.Data["Err_Admin"] = true
  181. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), tplInstall, form)
  182. return
  183. }
  184. // Check admin user creation
  185. if len(form.AdminName) > 0 {
  186. // Ensure AdminName is valid
  187. if err := models.IsUsableUsername(form.AdminName); err != nil {
  188. ctx.Data["Err_Admin"] = true
  189. ctx.Data["Err_AdminName"] = true
  190. if models.IsErrNameReserved(err) {
  191. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_reserved"), tplInstall, form)
  192. return
  193. } else if models.IsErrNamePatternNotAllowed(err) {
  194. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_pattern_not_allowed"), tplInstall, form)
  195. return
  196. }
  197. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_invalid"), tplInstall, form)
  198. return
  199. }
  200. // Check Admin email
  201. if len(form.AdminEmail) == 0 {
  202. ctx.Data["Err_Admin"] = true
  203. ctx.Data["Err_AdminEmail"] = true
  204. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_email"), tplInstall, form)
  205. return
  206. }
  207. // Check admin password.
  208. if len(form.AdminPasswd) == 0 {
  209. ctx.Data["Err_Admin"] = true
  210. ctx.Data["Err_AdminPasswd"] = true
  211. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), tplInstall, form)
  212. return
  213. }
  214. if form.AdminPasswd != form.AdminConfirmPasswd {
  215. ctx.Data["Err_Admin"] = true
  216. ctx.Data["Err_AdminPasswd"] = true
  217. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplInstall, form)
  218. return
  219. }
  220. }
  221. if form.AppURL[len(form.AppURL)-1] != '/' {
  222. form.AppURL += "/"
  223. }
  224. // Save settings.
  225. cfg := ini.Empty()
  226. if com.IsFile(setting.CustomConf) {
  227. // Keeps custom settings if there is already something.
  228. if err = cfg.Append(setting.CustomConf); err != nil {
  229. log.Error("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  230. }
  231. }
  232. cfg.Section("database").Key("DB_TYPE").SetValue(setting.Database.Type)
  233. cfg.Section("database").Key("HOST").SetValue(setting.Database.Host)
  234. cfg.Section("database").Key("NAME").SetValue(setting.Database.Name)
  235. cfg.Section("database").Key("USER").SetValue(setting.Database.User)
  236. cfg.Section("database").Key("PASSWD").SetValue(setting.Database.Passwd)
  237. cfg.Section("database").Key("SSL_MODE").SetValue(setting.Database.SSLMode)
  238. cfg.Section("database").Key("CHARSET").SetValue(setting.Database.Charset)
  239. cfg.Section("database").Key("PATH").SetValue(setting.Database.Path)
  240. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  241. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  242. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  243. cfg.Section("server").Key("SSH_DOMAIN").SetValue(form.Domain)
  244. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  245. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  246. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL)
  247. if form.SSHPort == 0 {
  248. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  249. } else {
  250. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  251. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  252. }
  253. if form.LFSRootPath != "" {
  254. cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
  255. cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
  256. var secretKey string
  257. if secretKey, err = generate.NewJwtSecret(); err != nil {
  258. ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
  259. return
  260. }
  261. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(secretKey)
  262. } else {
  263. cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
  264. }
  265. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  266. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  267. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  268. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  269. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  270. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  271. } else {
  272. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  273. }
  274. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  275. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  276. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  277. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  278. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  279. cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn))
  280. cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp))
  281. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  282. cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(com.ToStr(form.AllowOnlyExternalRegistration))
  283. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  284. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  285. cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate))
  286. cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization))
  287. cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking))
  288. cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress))
  289. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  290. cfg.Section("session").Key("PROVIDER").SetValue("file")
  291. cfg.Section("log").Key("MODE").SetValue("file")
  292. cfg.Section("log").Key("LEVEL").SetValue(setting.LogLevel)
  293. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  294. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  295. var secretKey string
  296. if secretKey, err = generate.NewSecretKey(); err != nil {
  297. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
  298. return
  299. }
  300. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  301. err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  302. if err != nil {
  303. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  304. return
  305. }
  306. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  307. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  308. return
  309. }
  310. GlobalInit(graceful.GetManager().HammerContext())
  311. // Create admin account
  312. if len(form.AdminName) > 0 {
  313. u := &models.User{
  314. Name: form.AdminName,
  315. Email: form.AdminEmail,
  316. Passwd: form.AdminPasswd,
  317. IsAdmin: true,
  318. IsActive: true,
  319. }
  320. if err = models.CreateUser(u); err != nil {
  321. if !models.IsErrUserAlreadyExist(err) {
  322. setting.InstallLock = false
  323. ctx.Data["Err_AdminName"] = true
  324. ctx.Data["Err_AdminEmail"] = true
  325. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form)
  326. return
  327. }
  328. log.Info("Admin account already exist")
  329. u, _ = models.GetUserByName(u.Name)
  330. }
  331. // Auto-login for admin
  332. if err = ctx.Session.Set("uid", u.ID); err != nil {
  333. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  334. return
  335. }
  336. if err = ctx.Session.Set("uname", u.Name); err != nil {
  337. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  338. return
  339. }
  340. if err = ctx.Session.Release(); err != nil {
  341. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  342. return
  343. }
  344. }
  345. log.Info("First-time run install finished!")
  346. // FIXME: This isn't really enough to completely take account of new configuration
  347. // We should really be restarting:
  348. // - On windows this is probably just a simple restart
  349. // - On linux we can't just use graceful.RestartProcess() everything that was passed in on LISTEN_FDS
  350. // (active or not) needs to be passed out and everything new passed out too.
  351. // This means we need to prevent the cleanup goroutine from running prior to the second GlobalInit
  352. ctx.Flash.Success(ctx.Tr("install.install_success"))
  353. ctx.Redirect(form.AppURL + "user/login")
  354. }