install.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "gopkg.in/ini.v1"
  15. "gopkg.in/macaron.v1"
  16. "github.com/gogits/git-module"
  17. "github.com/gogits/gogs/models"
  18. "github.com/gogits/gogs/modules/auth"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/context"
  21. "github.com/gogits/gogs/modules/cron"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/mailer"
  24. "github.com/gogits/gogs/modules/markdown"
  25. "github.com/gogits/gogs/modules/setting"
  26. "github.com/gogits/gogs/modules/ssh"
  27. "github.com/gogits/gogs/modules/template/highlight"
  28. "github.com/gogits/gogs/modules/user"
  29. )
  30. const (
  31. INSTALL base.TplName = "install"
  32. )
  33. func checkRunMode() {
  34. if setting.ProdMode {
  35. macaron.Env = macaron.PROD
  36. macaron.ColorLog = false
  37. } else {
  38. git.Debug = true
  39. }
  40. log.Info("Run Mode: %s", strings.Title(macaron.Env))
  41. }
  42. func NewServices() {
  43. setting.NewServices()
  44. mailer.NewContext()
  45. }
  46. // GlobalInit is for global configuration reload-able.
  47. func GlobalInit() {
  48. setting.NewContext()
  49. log.Trace("Custom path: %s", setting.CustomPath)
  50. log.Trace("Log path: %s", setting.LogRootPath)
  51. models.LoadConfigs()
  52. NewServices()
  53. if setting.InstallLock {
  54. highlight.NewContext()
  55. markdown.BuildSanitizer()
  56. if err := models.NewEngine(); err != nil {
  57. log.Fatal(4, "Fail to initialize ORM engine: %v", err)
  58. }
  59. models.HasEngine = true
  60. models.LoadRepoConfig()
  61. models.NewRepoContext()
  62. // Booting long running goroutines.
  63. cron.NewContext()
  64. models.InitSyncMirrors()
  65. models.InitDeliverHooks()
  66. models.InitTestPullRequests()
  67. log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
  68. }
  69. if models.EnableSQLite3 {
  70. log.Info("SQLite3 Supported")
  71. }
  72. if setting.SupportMiniWinService {
  73. log.Info("Builtin Windows Service Supported")
  74. }
  75. checkRunMode()
  76. if setting.InstallLock && setting.SSH.StartBuiltinServer {
  77. ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort)
  78. log.Info("SSH server started on %s:%v", setting.SSH.ListenHost, setting.SSH.ListenPort)
  79. }
  80. }
  81. func InstallInit(ctx *context.Context) {
  82. if setting.InstallLock {
  83. ctx.Handle(404, "Install", errors.New("Installation is prohibited"))
  84. return
  85. }
  86. ctx.Data["Title"] = ctx.Tr("install.install")
  87. ctx.Data["PageIsInstall"] = true
  88. dbOpts := []string{"MySQL", "PostgreSQL"}
  89. if models.EnableSQLite3 {
  90. dbOpts = append(dbOpts, "SQLite3")
  91. }
  92. ctx.Data["DbOptions"] = dbOpts
  93. }
  94. func Install(ctx *context.Context) {
  95. form := auth.InstallForm{}
  96. // Database settings
  97. form.DbHost = models.DbCfg.Host
  98. form.DbUser = models.DbCfg.User
  99. form.DbName = models.DbCfg.Name
  100. form.DbPath = models.DbCfg.Path
  101. ctx.Data["CurDbOption"] = "MySQL"
  102. switch models.DbCfg.Type {
  103. case "postgres":
  104. ctx.Data["CurDbOption"] = "PostgreSQL"
  105. case "sqlite3":
  106. if models.EnableSQLite3 {
  107. ctx.Data["CurDbOption"] = "SQLite3"
  108. }
  109. }
  110. // Application general settings
  111. form.AppName = setting.AppName
  112. form.RepoRootPath = setting.RepoRootPath
  113. // Note(unknwon): it's hard for Windows users change a running user,
  114. // so just use current one if config says default.
  115. if setting.IsWindows && setting.RunUser == "git" {
  116. form.RunUser = user.CurrentUsername()
  117. } else {
  118. form.RunUser = setting.RunUser
  119. }
  120. form.Domain = setting.Domain
  121. form.SSHPort = setting.SSH.Port
  122. form.HTTPPort = setting.HTTPPort
  123. form.AppUrl = setting.AppUrl
  124. form.LogRootPath = setting.LogRootPath
  125. // E-mail service settings
  126. if setting.MailService != nil {
  127. form.SMTPHost = setting.MailService.Host
  128. form.SMTPFrom = setting.MailService.From
  129. form.SMTPEmail = setting.MailService.User
  130. }
  131. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  132. form.MailNotify = setting.Service.EnableNotifyMail
  133. // Server and other services settings
  134. form.OfflineMode = setting.OfflineMode
  135. form.DisableGravatar = setting.DisableGravatar
  136. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  137. form.DisableRegistration = setting.Service.DisableRegistration
  138. form.EnableCaptcha = setting.Service.EnableCaptcha
  139. form.RequireSignInView = setting.Service.RequireSignInView
  140. auth.AssignForm(form, ctx.Data)
  141. ctx.HTML(200, INSTALL)
  142. }
  143. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  144. ctx.Data["CurDbOption"] = form.DbType
  145. if ctx.HasError() {
  146. if ctx.HasValue("Err_SMTPEmail") {
  147. ctx.Data["Err_SMTP"] = true
  148. }
  149. if ctx.HasValue("Err_AdminName") ||
  150. ctx.HasValue("Err_AdminPasswd") ||
  151. ctx.HasValue("Err_AdminEmail") {
  152. ctx.Data["Err_Admin"] = true
  153. }
  154. ctx.HTML(200, INSTALL)
  155. return
  156. }
  157. if _, err := exec.LookPath("git"); err != nil {
  158. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form)
  159. return
  160. }
  161. // Pass basic check, now test configuration.
  162. // Test database setting.
  163. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "SQLite3": "sqlite3", "TiDB": "tidb"}
  164. models.DbCfg.Type = dbTypes[form.DbType]
  165. models.DbCfg.Host = form.DbHost
  166. models.DbCfg.User = form.DbUser
  167. models.DbCfg.Passwd = form.DbPasswd
  168. models.DbCfg.Name = form.DbName
  169. models.DbCfg.SSLMode = form.SSLMode
  170. models.DbCfg.Path = form.DbPath
  171. if (models.DbCfg.Type == "sqlite3" || models.DbCfg.Type == "tidb") &&
  172. len(models.DbCfg.Path) == 0 {
  173. ctx.Data["Err_DbPath"] = true
  174. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &form)
  175. return
  176. } else if models.DbCfg.Type == "tidb" &&
  177. strings.ContainsAny(path.Base(models.DbCfg.Path), ".-") {
  178. ctx.Data["Err_DbPath"] = true
  179. ctx.RenderWithErr(ctx.Tr("install.err_invalid_tidb_name"), INSTALL, &form)
  180. return
  181. }
  182. // Set test engine.
  183. var x *xorm.Engine
  184. if err := models.NewTestEngine(x); err != nil {
  185. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  186. ctx.Data["Err_DbType"] = true
  187. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &form)
  188. } else {
  189. ctx.Data["Err_DbSetting"] = true
  190. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form)
  191. }
  192. return
  193. }
  194. // Test repository root path.
  195. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  196. if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  197. ctx.Data["Err_RepoRootPath"] = true
  198. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form)
  199. return
  200. }
  201. // Test log root path.
  202. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  203. if err := os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  204. ctx.Data["Err_LogRootPath"] = true
  205. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &form)
  206. return
  207. }
  208. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  209. if !match {
  210. ctx.Data["Err_RunUser"] = true
  211. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), INSTALL, &form)
  212. return
  213. }
  214. // Check logic loophole between disable self-registration and no admin account.
  215. if form.DisableRegistration && len(form.AdminName) == 0 {
  216. ctx.Data["Err_Services"] = true
  217. ctx.Data["Err_Admin"] = true
  218. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, form)
  219. return
  220. }
  221. // Check admin password.
  222. if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 {
  223. ctx.Data["Err_Admin"] = true
  224. ctx.Data["Err_AdminPasswd"] = true
  225. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, form)
  226. return
  227. }
  228. if form.AdminPasswd != form.AdminConfirmPasswd {
  229. ctx.Data["Err_Admin"] = true
  230. ctx.Data["Err_AdminPasswd"] = true
  231. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form)
  232. return
  233. }
  234. if form.AppUrl[len(form.AppUrl)-1] != '/' {
  235. form.AppUrl += "/"
  236. }
  237. // Save settings.
  238. cfg := ini.Empty()
  239. if com.IsFile(setting.CustomConf) {
  240. // Keeps custom settings if there is already something.
  241. if err := cfg.Append(setting.CustomConf); err != nil {
  242. log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err)
  243. }
  244. }
  245. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  246. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  247. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  248. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  249. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  250. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  251. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  252. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  253. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  254. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  255. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  256. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  257. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl)
  258. if form.SSHPort == 0 {
  259. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  260. } else {
  261. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  262. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  263. }
  264. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  265. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  266. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  267. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  268. cfg.Section("mailer").Key("USER").SetValue(form.SMTPEmail)
  269. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  270. } else {
  271. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  272. }
  273. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  274. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  275. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  276. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  277. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  278. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  279. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  280. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  281. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  282. cfg.Section("session").Key("PROVIDER").SetValue("file")
  283. cfg.Section("log").Key("MODE").SetValue("file")
  284. cfg.Section("log").Key("LEVEL").SetValue("Info")
  285. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  286. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  287. secretKey, err := base.GetRandomString(15)
  288. if err != nil {
  289. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &form)
  290. return
  291. }
  292. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  293. os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  294. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  295. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form)
  296. return
  297. }
  298. GlobalInit()
  299. // Create admin account
  300. if len(form.AdminName) > 0 {
  301. u := &models.User{
  302. Name: form.AdminName,
  303. Email: form.AdminEmail,
  304. Passwd: form.AdminPasswd,
  305. IsAdmin: true,
  306. IsActive: true,
  307. }
  308. if err := models.CreateUser(u); err != nil {
  309. if !models.IsErrUserAlreadyExist(err) {
  310. setting.InstallLock = false
  311. ctx.Data["Err_AdminName"] = true
  312. ctx.Data["Err_AdminEmail"] = true
  313. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form)
  314. return
  315. }
  316. log.Info("Admin account already exist")
  317. u, _ = models.GetUserByName(u.Name)
  318. }
  319. // Auto-login for admin
  320. ctx.Session.Set("uid", u.ID)
  321. ctx.Session.Set("uname", u.Name)
  322. }
  323. log.Info("First-time run install finished!")
  324. ctx.Flash.Success(ctx.Tr("install.install_success"))
  325. ctx.Redirect(form.AppUrl + "user/login")
  326. }