install.go 12 KB

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