install.go 12 KB

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