install.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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(2, "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", "MSSQL"}
  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 "mssql":
  107. ctx.Data["CurDbOption"] = "MSSQL"
  108. case "sqlite3":
  109. if models.EnableSQLite3 {
  110. ctx.Data["CurDbOption"] = "SQLite3"
  111. }
  112. }
  113. // Application general settings
  114. form.AppName = setting.AppName
  115. form.RepoRootPath = setting.RepoRootPath
  116. // Note(unknwon): it's hard for Windows users change a running user,
  117. // so just use current one if config says default.
  118. if setting.IsWindows && setting.RunUser == "git" {
  119. form.RunUser = user.CurrentUsername()
  120. } else {
  121. form.RunUser = setting.RunUser
  122. }
  123. form.Domain = setting.Domain
  124. form.SSHPort = setting.SSH.Port
  125. form.HTTPPort = setting.HTTPPort
  126. form.AppUrl = setting.AppUrl
  127. form.LogRootPath = setting.LogRootPath
  128. // E-mail service settings
  129. if setting.MailService != nil {
  130. form.SMTPHost = setting.MailService.Host
  131. form.SMTPFrom = setting.MailService.From
  132. form.SMTPUser = setting.MailService.User
  133. }
  134. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  135. form.MailNotify = setting.Service.EnableNotifyMail
  136. // Server and other services settings
  137. form.OfflineMode = setting.OfflineMode
  138. form.DisableGravatar = setting.DisableGravatar
  139. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  140. form.DisableRegistration = setting.Service.DisableRegistration
  141. form.EnableCaptcha = setting.Service.EnableCaptcha
  142. form.RequireSignInView = setting.Service.RequireSignInView
  143. auth.AssignForm(form, ctx.Data)
  144. ctx.HTML(200, INSTALL)
  145. }
  146. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  147. ctx.Data["CurDbOption"] = form.DbType
  148. if ctx.HasError() {
  149. if ctx.HasValue("Err_SMTPEmail") {
  150. ctx.Data["Err_SMTP"] = true
  151. }
  152. if ctx.HasValue("Err_AdminName") ||
  153. ctx.HasValue("Err_AdminPasswd") ||
  154. ctx.HasValue("Err_AdminEmail") {
  155. ctx.Data["Err_Admin"] = true
  156. }
  157. ctx.HTML(200, INSTALL)
  158. return
  159. }
  160. if _, err := exec.LookPath("git"); err != nil {
  161. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form)
  162. return
  163. }
  164. // Pass basic check, now test configuration.
  165. // Test database setting.
  166. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"}
  167. models.DbCfg.Type = dbTypes[form.DbType]
  168. models.DbCfg.Host = form.DbHost
  169. models.DbCfg.User = form.DbUser
  170. models.DbCfg.Passwd = form.DbPasswd
  171. models.DbCfg.Name = form.DbName
  172. models.DbCfg.SSLMode = form.SSLMode
  173. models.DbCfg.Path = form.DbPath
  174. if (models.DbCfg.Type == "sqlite3" || models.DbCfg.Type == "tidb") &&
  175. len(models.DbCfg.Path) == 0 {
  176. ctx.Data["Err_DbPath"] = true
  177. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &form)
  178. return
  179. } else if models.DbCfg.Type == "tidb" &&
  180. strings.ContainsAny(path.Base(models.DbCfg.Path), ".-") {
  181. ctx.Data["Err_DbPath"] = true
  182. ctx.RenderWithErr(ctx.Tr("install.err_invalid_tidb_name"), INSTALL, &form)
  183. return
  184. }
  185. // Set test engine.
  186. var x *xorm.Engine
  187. if err := models.NewTestEngine(x); err != nil {
  188. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  189. ctx.Data["Err_DbType"] = true
  190. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &form)
  191. } else {
  192. ctx.Data["Err_DbSetting"] = true
  193. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form)
  194. }
  195. return
  196. }
  197. // Test repository root path.
  198. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  199. if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  200. ctx.Data["Err_RepoRootPath"] = true
  201. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form)
  202. return
  203. }
  204. // Test log root path.
  205. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  206. if err := os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  207. ctx.Data["Err_LogRootPath"] = true
  208. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &form)
  209. return
  210. }
  211. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  212. if !match {
  213. ctx.Data["Err_RunUser"] = true
  214. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), INSTALL, &form)
  215. return
  216. }
  217. // Make sure FROM field is valid
  218. if len(form.SMTPFrom) > 0 {
  219. _, err := mail.ParseAddress(form.SMTPFrom)
  220. if err != nil {
  221. ctx.Data["Err_SMTP"] = true
  222. ctx.Data["Err_SMTPFrom"] = true
  223. ctx.RenderWithErr(ctx.Tr("install.invalid_smtp_from", err), INSTALL, &form)
  224. return
  225. }
  226. }
  227. // Check logic loophole between disable self-registration and no admin account.
  228. if form.DisableRegistration && len(form.AdminName) == 0 {
  229. ctx.Data["Err_Services"] = true
  230. ctx.Data["Err_Admin"] = true
  231. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, form)
  232. return
  233. }
  234. // Check admin password.
  235. if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 {
  236. ctx.Data["Err_Admin"] = true
  237. ctx.Data["Err_AdminPasswd"] = true
  238. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, form)
  239. return
  240. }
  241. if form.AdminPasswd != form.AdminConfirmPasswd {
  242. ctx.Data["Err_Admin"] = true
  243. ctx.Data["Err_AdminPasswd"] = true
  244. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form)
  245. return
  246. }
  247. if form.AppUrl[len(form.AppUrl)-1] != '/' {
  248. form.AppUrl += "/"
  249. }
  250. // Save settings.
  251. cfg := ini.Empty()
  252. if com.IsFile(setting.CustomConf) {
  253. // Keeps custom settings if there is already something.
  254. if err := cfg.Append(setting.CustomConf); err != nil {
  255. log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err)
  256. }
  257. }
  258. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  259. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  260. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  261. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  262. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  263. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  264. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  265. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  266. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  267. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  268. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  269. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  270. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl)
  271. if form.SSHPort == 0 {
  272. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  273. } else {
  274. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  275. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  276. }
  277. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  278. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  279. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  280. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  281. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  282. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  283. } else {
  284. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  285. }
  286. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  287. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  288. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  289. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  290. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  291. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  292. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  293. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  294. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  295. cfg.Section("session").Key("PROVIDER").SetValue("file")
  296. cfg.Section("log").Key("MODE").SetValue("file")
  297. cfg.Section("log").Key("LEVEL").SetValue("Info")
  298. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  299. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  300. secretKey, err := base.GetRandomString(15)
  301. if err != nil {
  302. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &form)
  303. return
  304. }
  305. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  306. os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  307. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  308. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form)
  309. return
  310. }
  311. GlobalInit()
  312. // Create admin account
  313. if len(form.AdminName) > 0 {
  314. u := &models.User{
  315. Name: form.AdminName,
  316. Email: form.AdminEmail,
  317. Passwd: form.AdminPasswd,
  318. IsAdmin: true,
  319. IsActive: true,
  320. }
  321. if err := models.CreateUser(u); err != nil {
  322. if !models.IsErrUserAlreadyExist(err) {
  323. setting.InstallLock = false
  324. ctx.Data["Err_AdminName"] = true
  325. ctx.Data["Err_AdminEmail"] = true
  326. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form)
  327. return
  328. }
  329. log.Info("Admin account already exist")
  330. u, _ = models.GetUserByName(u.Name)
  331. }
  332. // Auto-login for admin
  333. ctx.Session.Set("uid", u.ID)
  334. ctx.Session.Set("uname", u.Name)
  335. }
  336. log.Info("First-time run install finished!")
  337. ctx.Flash.Success(ctx.Tr("install.install_success"))
  338. ctx.Redirect(form.AppUrl + "user/login")
  339. }