install.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. log "gopkg.in/clog.v1"
  15. "gopkg.in/ini.v1"
  16. "gopkg.in/macaron.v1"
  17. "github.com/gogits/git-module"
  18. "github.com/gogits/gogs/models"
  19. "github.com/gogits/gogs/pkg/context"
  20. "github.com/gogits/gogs/pkg/cron"
  21. "github.com/gogits/gogs/pkg/form"
  22. "github.com/gogits/gogs/pkg/mailer"
  23. "github.com/gogits/gogs/pkg/markup"
  24. "github.com/gogits/gogs/pkg/setting"
  25. "github.com/gogits/gogs/pkg/ssh"
  26. "github.com/gogits/gogs/pkg/template/highlight"
  27. "github.com/gogits/gogs/pkg/tool"
  28. "github.com/gogits/gogs/pkg/user"
  29. )
  30. const (
  31. INSTALL = "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. markup.NewSanitizer()
  56. if err := models.NewEngine(); err != nil {
  57. log.Fatal(2, "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. }
  68. if models.EnableSQLite3 {
  69. log.Info("SQLite3 Supported")
  70. }
  71. if setting.SupportMiniWinService {
  72. log.Info("Builtin Windows Service Supported")
  73. }
  74. checkRunMode()
  75. if setting.InstallLock && setting.SSH.StartBuiltinServer {
  76. ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers)
  77. log.Info("SSH server started on %s:%v", setting.SSH.ListenHost, setting.SSH.ListenPort)
  78. log.Trace("SSH server cipher list: %v", setting.SSH.ServerCiphers)
  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", "MSSQL"}
  89. if models.EnableSQLite3 {
  90. dbOpts = append(dbOpts, "SQLite3")
  91. }
  92. ctx.Data["DbOptions"] = dbOpts
  93. }
  94. func Install(ctx *context.Context) {
  95. f := form.Install{}
  96. // Database settings
  97. f.DbHost = models.DbCfg.Host
  98. f.DbUser = models.DbCfg.User
  99. f.DbName = models.DbCfg.Name
  100. f.DbPath = models.DbCfg.Path
  101. ctx.Data["CurDbOption"] = "MySQL"
  102. switch models.DbCfg.Type {
  103. case "postgres":
  104. ctx.Data["CurDbOption"] = "PostgreSQL"
  105. case "mssql":
  106. ctx.Data["CurDbOption"] = "MSSQL"
  107. case "sqlite3":
  108. if models.EnableSQLite3 {
  109. ctx.Data["CurDbOption"] = "SQLite3"
  110. }
  111. }
  112. // Application general settings
  113. f.AppName = setting.AppName
  114. f.RepoRootPath = setting.RepoRootPath
  115. // Note(unknwon): it's hard for Windows users change a running user,
  116. // so just use current one if config says default.
  117. if setting.IsWindows && setting.RunUser == "git" {
  118. f.RunUser = user.CurrentUsername()
  119. } else {
  120. f.RunUser = setting.RunUser
  121. }
  122. f.Domain = setting.Domain
  123. f.SSHPort = setting.SSH.Port
  124. f.UseBuiltinSSHServer = setting.SSH.StartBuiltinServer
  125. f.HTTPPort = setting.HTTPPort
  126. f.AppUrl = setting.AppURL
  127. f.LogRootPath = setting.LogRootPath
  128. // E-mail service settings
  129. if setting.MailService != nil {
  130. f.SMTPHost = setting.MailService.Host
  131. f.SMTPFrom = setting.MailService.From
  132. f.SMTPUser = setting.MailService.User
  133. }
  134. f.RegisterConfirm = setting.Service.RegisterEmailConfirm
  135. f.MailNotify = setting.Service.EnableNotifyMail
  136. // Server and other services settings
  137. f.OfflineMode = setting.OfflineMode
  138. f.DisableGravatar = setting.DisableGravatar
  139. f.EnableFederatedAvatar = setting.EnableFederatedAvatar
  140. f.DisableRegistration = setting.Service.DisableRegistration
  141. f.EnableCaptcha = setting.Service.EnableCaptcha
  142. f.RequireSignInView = setting.Service.RequireSignInView
  143. form.Assign(f, ctx.Data)
  144. ctx.HTML(200, INSTALL)
  145. }
  146. func InstallPost(ctx *context.Context, f form.Install) {
  147. ctx.Data["CurDbOption"] = f.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, &f)
  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[f.DbType]
  168. models.DbCfg.Host = f.DbHost
  169. models.DbCfg.User = f.DbUser
  170. models.DbCfg.Passwd = f.DbPasswd
  171. models.DbCfg.Name = f.DbName
  172. models.DbCfg.SSLMode = f.SSLMode
  173. models.DbCfg.Path = f.DbPath
  174. if models.DbCfg.Type == "sqlite3" && len(models.DbCfg.Path) == 0 {
  175. ctx.Data["Err_DbPath"] = true
  176. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &f)
  177. return
  178. }
  179. // Set test engine.
  180. var x *xorm.Engine
  181. if err := models.NewTestEngine(x); err != nil {
  182. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  183. ctx.Data["Err_DbType"] = true
  184. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
  185. } else {
  186. ctx.Data["Err_DbSetting"] = true
  187. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &f)
  188. }
  189. return
  190. }
  191. // Test repository root path.
  192. f.RepoRootPath = strings.Replace(f.RepoRootPath, "\\", "/", -1)
  193. if err := os.MkdirAll(f.RepoRootPath, os.ModePerm); err != nil {
  194. ctx.Data["Err_RepoRootPath"] = true
  195. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &f)
  196. return
  197. }
  198. // Test log root path.
  199. f.LogRootPath = strings.Replace(f.LogRootPath, "\\", "/", -1)
  200. if err := os.MkdirAll(f.LogRootPath, os.ModePerm); err != nil {
  201. ctx.Data["Err_LogRootPath"] = true
  202. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &f)
  203. return
  204. }
  205. currentUser, match := setting.IsRunUserMatchCurrentUser(f.RunUser)
  206. if !match {
  207. ctx.Data["Err_RunUser"] = true
  208. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", f.RunUser, currentUser), INSTALL, &f)
  209. return
  210. }
  211. // Make sure FROM field is valid
  212. if len(f.SMTPFrom) > 0 {
  213. _, err := mail.ParseAddress(f.SMTPFrom)
  214. if err != nil {
  215. ctx.Data["Err_SMTP"] = true
  216. ctx.Data["Err_SMTPFrom"] = true
  217. ctx.RenderWithErr(ctx.Tr("install.invalid_smtp_from", err), INSTALL, &f)
  218. return
  219. }
  220. }
  221. // Check logic loophole between disable self-registration and no admin account.
  222. if f.DisableRegistration && len(f.AdminName) == 0 {
  223. ctx.Data["Err_Services"] = true
  224. ctx.Data["Err_Admin"] = true
  225. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, f)
  226. return
  227. }
  228. // Check admin password.
  229. if len(f.AdminName) > 0 && len(f.AdminPasswd) == 0 {
  230. ctx.Data["Err_Admin"] = true
  231. ctx.Data["Err_AdminPasswd"] = true
  232. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, f)
  233. return
  234. }
  235. if f.AdminPasswd != f.AdminConfirmPasswd {
  236. ctx.Data["Err_Admin"] = true
  237. ctx.Data["Err_AdminPasswd"] = true
  238. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, f)
  239. return
  240. }
  241. if f.AppUrl[len(f.AppUrl)-1] != '/' {
  242. f.AppUrl += "/"
  243. }
  244. // Save settings.
  245. cfg := ini.Empty()
  246. if com.IsFile(setting.CustomConf) {
  247. // Keeps custom settings if there is already something.
  248. if err := cfg.Append(setting.CustomConf); err != nil {
  249. log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err)
  250. }
  251. }
  252. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  253. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  254. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  255. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  256. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  257. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  258. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  259. cfg.Section("").Key("APP_NAME").SetValue(f.AppName)
  260. cfg.Section("repository").Key("ROOT").SetValue(f.RepoRootPath)
  261. cfg.Section("").Key("RUN_USER").SetValue(f.RunUser)
  262. cfg.Section("server").Key("DOMAIN").SetValue(f.Domain)
  263. cfg.Section("server").Key("HTTP_PORT").SetValue(f.HTTPPort)
  264. cfg.Section("server").Key("ROOT_URL").SetValue(f.AppUrl)
  265. if f.SSHPort == 0 {
  266. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  267. } else {
  268. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  269. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(f.SSHPort))
  270. cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(f.UseBuiltinSSHServer))
  271. }
  272. if len(strings.TrimSpace(f.SMTPHost)) > 0 {
  273. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  274. cfg.Section("mailer").Key("HOST").SetValue(f.SMTPHost)
  275. cfg.Section("mailer").Key("FROM").SetValue(f.SMTPFrom)
  276. cfg.Section("mailer").Key("USER").SetValue(f.SMTPUser)
  277. cfg.Section("mailer").Key("PASSWD").SetValue(f.SMTPPasswd)
  278. } else {
  279. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  280. }
  281. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(f.RegisterConfirm))
  282. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(f.MailNotify))
  283. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(f.OfflineMode))
  284. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(f.DisableGravatar))
  285. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(f.EnableFederatedAvatar))
  286. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(f.DisableRegistration))
  287. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(f.EnableCaptcha))
  288. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(f.RequireSignInView))
  289. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  290. cfg.Section("session").Key("PROVIDER").SetValue("file")
  291. mode := "file"
  292. if f.EnableConsoleMode {
  293. mode = "console, file"
  294. }
  295. cfg.Section("log").Key("MODE").SetValue(mode)
  296. cfg.Section("log").Key("LEVEL").SetValue("Info")
  297. cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath)
  298. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  299. secretKey, err := tool.RandomString(15)
  300. if err != nil {
  301. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &f)
  302. return
  303. }
  304. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  305. os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  306. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  307. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &f)
  308. return
  309. }
  310. GlobalInit()
  311. // Create admin account
  312. if len(f.AdminName) > 0 {
  313. u := &models.User{
  314. Name: f.AdminName,
  315. Email: f.AdminEmail,
  316. Passwd: f.AdminPasswd,
  317. IsAdmin: true,
  318. IsActive: true,
  319. }
  320. if err := models.CreateUser(u); err != nil {
  321. if !models.IsErrUserAlreadyExist(err) {
  322. setting.InstallLock = false
  323. ctx.Data["Err_AdminName"] = true
  324. ctx.Data["Err_AdminEmail"] = true
  325. ctx.RenderWithErr(ctx.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. ctx.Session.Set("uid", u.ID)
  333. ctx.Session.Set("uname", u.Name)
  334. }
  335. log.Info("First-time run install finished!")
  336. ctx.Flash.Success(ctx.Tr("install.install_success"))
  337. ctx.Redirect(f.AppUrl + "user/login")
  338. }