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