install.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 route
  5. import (
  6. "net/mail"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "github.com/pkg/errors"
  12. "github.com/unknwon/com"
  13. "gopkg.in/ini.v1"
  14. "gopkg.in/macaron.v1"
  15. log "unknwon.dev/clog/v2"
  16. "xorm.io/xorm"
  17. "github.com/gogs/git-module"
  18. "gogs.io/gogs/internal/conf"
  19. "gogs.io/gogs/internal/context"
  20. "gogs.io/gogs/internal/cron"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/form"
  23. "gogs.io/gogs/internal/mailer"
  24. "gogs.io/gogs/internal/markup"
  25. "gogs.io/gogs/internal/osutil"
  26. "gogs.io/gogs/internal/ssh"
  27. "gogs.io/gogs/internal/template/highlight"
  28. "gogs.io/gogs/internal/tool"
  29. )
  30. const (
  31. INSTALL = "install"
  32. )
  33. func checkRunMode() {
  34. if conf.IsProdMode() {
  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. // GlobalInit is for global configuration reload-able.
  43. func GlobalInit(customConf string) error {
  44. err := conf.Init(customConf)
  45. if err != nil {
  46. return errors.Wrap(err, "init configuration")
  47. }
  48. conf.InitLogging()
  49. log.Info("%s %s", conf.App.BrandName, conf.App.Version)
  50. log.Trace("Work directory: %s", conf.WorkDir())
  51. log.Trace("Custom path: %s", conf.CustomDir())
  52. log.Trace("Custom config: %s", conf.CustomConf)
  53. log.Trace("Log path: %s", conf.LogRootPath)
  54. log.Trace("Build time: %s", conf.BuildTime)
  55. log.Trace("Build commit: %s", conf.BuildCommit)
  56. conf.NewServices()
  57. mailer.NewContext()
  58. if conf.Security.InstallLock {
  59. highlight.NewContext()
  60. markup.NewSanitizer()
  61. if err := db.NewEngine(); err != nil {
  62. log.Fatal("Failed to initialize ORM engine: %v", err)
  63. }
  64. db.HasEngine = true
  65. db.LoadAuthSources()
  66. db.LoadRepoConfig()
  67. db.NewRepoContext()
  68. // Booting long running goroutines.
  69. cron.NewContext()
  70. db.InitSyncMirrors()
  71. db.InitDeliverHooks()
  72. db.InitTestPullRequests()
  73. }
  74. if db.EnableSQLite3 {
  75. log.Info("SQLite3 is supported")
  76. }
  77. if conf.HasMinWinSvc {
  78. log.Info("Builtin Windows Service is supported")
  79. }
  80. if conf.Server.LoadAssetsFromDisk {
  81. log.Trace("Assets are loaded from disk")
  82. }
  83. checkRunMode()
  84. if !conf.Security.InstallLock {
  85. return nil
  86. }
  87. if conf.SSH.StartBuiltinServer {
  88. ssh.Listen(conf.SSH.ListenHost, conf.SSH.ListenPort, conf.SSH.ServerCiphers)
  89. log.Info("SSH server started on %s:%v", conf.SSH.ListenHost, conf.SSH.ListenPort)
  90. log.Trace("SSH server cipher list: %v", conf.SSH.ServerCiphers)
  91. }
  92. if conf.SSH.RewriteAuthorizedKeysAtStart {
  93. if err := db.RewriteAuthorizedKeys(); err != nil {
  94. log.Warn("Failed to rewrite authorized_keys file: %v", err)
  95. }
  96. }
  97. return nil
  98. }
  99. func InstallInit(c *context.Context) {
  100. if conf.Security.InstallLock {
  101. c.NotFound()
  102. return
  103. }
  104. c.Title("install.install")
  105. c.PageIs("Install")
  106. dbOpts := []string{"MySQL", "PostgreSQL", "MSSQL"}
  107. if db.EnableSQLite3 {
  108. dbOpts = append(dbOpts, "SQLite3")
  109. }
  110. c.Data["DbOptions"] = dbOpts
  111. }
  112. func Install(c *context.Context) {
  113. f := form.Install{}
  114. // Database settings
  115. f.DbHost = conf.Database.Host
  116. f.DbUser = conf.Database.User
  117. f.DbName = conf.Database.Name
  118. f.DbPath = conf.Database.Path
  119. c.Data["CurDbOption"] = "PostgreSQL"
  120. switch conf.Database.Type {
  121. case "mysql":
  122. c.Data["CurDbOption"] = "MySQL"
  123. case "mssql":
  124. c.Data["CurDbOption"] = "MSSQL"
  125. case "sqlite3":
  126. if db.EnableSQLite3 {
  127. c.Data["CurDbOption"] = "SQLite3"
  128. }
  129. }
  130. // Application general settings
  131. f.AppName = conf.App.BrandName
  132. f.RepoRootPath = conf.Repository.Root
  133. // Note(unknwon): it's hard for Windows users change a running user,
  134. // so just use current one if config says default.
  135. if conf.IsWindowsRuntime() && conf.App.RunUser == "git" {
  136. f.RunUser = osutil.CurrentUsername()
  137. } else {
  138. f.RunUser = conf.App.RunUser
  139. }
  140. f.Domain = conf.Server.Domain
  141. f.SSHPort = conf.SSH.Port
  142. f.UseBuiltinSSHServer = conf.SSH.StartBuiltinServer
  143. f.HTTPPort = conf.Server.HTTPPort
  144. f.AppUrl = conf.Server.ExternalURL
  145. f.LogRootPath = conf.LogRootPath
  146. // E-mail service settings
  147. if conf.MailService != nil {
  148. f.SMTPHost = conf.MailService.Host
  149. f.SMTPFrom = conf.MailService.From
  150. f.SMTPUser = conf.MailService.User
  151. }
  152. f.RegisterConfirm = conf.Service.RegisterEmailConfirm
  153. f.MailNotify = conf.Service.EnableNotifyMail
  154. // Server and other services settings
  155. f.OfflineMode = conf.Server.OfflineMode
  156. f.DisableGravatar = conf.DisableGravatar
  157. f.EnableFederatedAvatar = conf.EnableFederatedAvatar
  158. f.DisableRegistration = conf.Service.DisableRegistration
  159. f.EnableCaptcha = conf.Service.EnableCaptcha
  160. f.RequireSignInView = conf.Service.RequireSignInView
  161. form.Assign(f, c.Data)
  162. c.Success(INSTALL)
  163. }
  164. func InstallPost(c *context.Context, f form.Install) {
  165. c.Data["CurDbOption"] = f.DbType
  166. if c.HasError() {
  167. if c.HasValue("Err_SMTPEmail") {
  168. c.FormErr("SMTP")
  169. }
  170. if c.HasValue("Err_AdminName") ||
  171. c.HasValue("Err_AdminPasswd") ||
  172. c.HasValue("Err_AdminEmail") {
  173. c.FormErr("Admin")
  174. }
  175. c.Success(INSTALL)
  176. return
  177. }
  178. if _, err := exec.LookPath("git"); err != nil {
  179. c.RenderWithErr(c.Tr("install.test_git_failed", err), INSTALL, &f)
  180. return
  181. }
  182. // Pass basic check, now test configuration.
  183. // Test database setting.
  184. dbTypes := map[string]string{
  185. "PostgreSQL": "postgres",
  186. "MySQL": "mysql",
  187. "MSSQL": "mssql",
  188. "SQLite3": "sqlite3",
  189. }
  190. conf.Database.Type = dbTypes[f.DbType]
  191. conf.Database.Host = f.DbHost
  192. conf.Database.User = f.DbUser
  193. conf.Database.Password = f.DbPasswd
  194. conf.Database.Name = f.DbName
  195. conf.Database.SSLMode = f.SSLMode
  196. conf.Database.Path = f.DbPath
  197. if conf.Database.Type == "sqlite3" && len(conf.Database.Path) == 0 {
  198. c.FormErr("DbPath")
  199. c.RenderWithErr(c.Tr("install.err_empty_db_path"), INSTALL, &f)
  200. return
  201. }
  202. // Set test engine.
  203. var x *xorm.Engine
  204. if err := db.NewTestEngine(x); err != nil {
  205. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  206. c.FormErr("DbType")
  207. c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
  208. } else {
  209. c.FormErr("DbSetting")
  210. c.RenderWithErr(c.Tr("install.invalid_db_setting", err), INSTALL, &f)
  211. }
  212. return
  213. }
  214. // Test repository root path.
  215. f.RepoRootPath = strings.Replace(f.RepoRootPath, "\\", "/", -1)
  216. if err := os.MkdirAll(f.RepoRootPath, os.ModePerm); err != nil {
  217. c.FormErr("RepoRootPath")
  218. c.RenderWithErr(c.Tr("install.invalid_repo_path", err), INSTALL, &f)
  219. return
  220. }
  221. // Test log root path.
  222. f.LogRootPath = strings.Replace(f.LogRootPath, "\\", "/", -1)
  223. if err := os.MkdirAll(f.LogRootPath, os.ModePerm); err != nil {
  224. c.FormErr("LogRootPath")
  225. c.RenderWithErr(c.Tr("install.invalid_log_root_path", err), INSTALL, &f)
  226. return
  227. }
  228. currentUser, match := conf.CheckRunUser(f.RunUser)
  229. if !match {
  230. c.FormErr("RunUser")
  231. c.RenderWithErr(c.Tr("install.run_user_not_match", f.RunUser, currentUser), INSTALL, &f)
  232. return
  233. }
  234. // Check host address and port
  235. if len(f.SMTPHost) > 0 && !strings.Contains(f.SMTPHost, ":") {
  236. c.FormErr("SMTP", "SMTPHost")
  237. c.RenderWithErr(c.Tr("install.smtp_host_missing_port"), INSTALL, &f)
  238. return
  239. }
  240. // Make sure FROM field is valid
  241. if len(f.SMTPFrom) > 0 {
  242. _, err := mail.ParseAddress(f.SMTPFrom)
  243. if err != nil {
  244. c.FormErr("SMTP", "SMTPFrom")
  245. c.RenderWithErr(c.Tr("install.invalid_smtp_from", err), INSTALL, &f)
  246. return
  247. }
  248. }
  249. // Check logic loophole between disable self-registration and no admin account.
  250. if f.DisableRegistration && len(f.AdminName) == 0 {
  251. c.FormErr("Services", "Admin")
  252. c.RenderWithErr(c.Tr("install.no_admin_and_disable_registration"), INSTALL, f)
  253. return
  254. }
  255. // Check admin password.
  256. if len(f.AdminName) > 0 && len(f.AdminPasswd) == 0 {
  257. c.FormErr("Admin", "AdminPasswd")
  258. c.RenderWithErr(c.Tr("install.err_empty_admin_password"), INSTALL, f)
  259. return
  260. }
  261. if f.AdminPasswd != f.AdminConfirmPasswd {
  262. c.FormErr("Admin", "AdminPasswd")
  263. c.RenderWithErr(c.Tr("form.password_not_match"), INSTALL, f)
  264. return
  265. }
  266. if f.AppUrl[len(f.AppUrl)-1] != '/' {
  267. f.AppUrl += "/"
  268. }
  269. // Save settings.
  270. cfg := ini.Empty()
  271. if osutil.IsFile(conf.CustomConf) {
  272. // Keeps custom settings if there is already something.
  273. if err := cfg.Append(conf.CustomConf); err != nil {
  274. log.Error("Failed to load custom conf %q: %v", conf.CustomConf, err)
  275. }
  276. }
  277. cfg.Section("database").Key("TYPE").SetValue(conf.Database.Type)
  278. cfg.Section("database").Key("HOST").SetValue(conf.Database.Host)
  279. cfg.Section("database").Key("NAME").SetValue(conf.Database.Name)
  280. cfg.Section("database").Key("USER").SetValue(conf.Database.User)
  281. cfg.Section("database").Key("PASSWORD").SetValue(conf.Database.Password)
  282. cfg.Section("database").Key("SSL_MODE").SetValue(conf.Database.SSLMode)
  283. cfg.Section("database").Key("PATH").SetValue(conf.Database.Path)
  284. cfg.Section("").Key("BRAND_NAME").SetValue(f.AppName)
  285. cfg.Section("repository").Key("ROOT").SetValue(f.RepoRootPath)
  286. cfg.Section("").Key("RUN_USER").SetValue(f.RunUser)
  287. cfg.Section("server").Key("DOMAIN").SetValue(f.Domain)
  288. cfg.Section("server").Key("HTTP_PORT").SetValue(f.HTTPPort)
  289. cfg.Section("server").Key("EXTERNAL_URL").SetValue(f.AppUrl)
  290. if f.SSHPort == 0 {
  291. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  292. } else {
  293. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  294. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(f.SSHPort))
  295. cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(f.UseBuiltinSSHServer))
  296. }
  297. if len(strings.TrimSpace(f.SMTPHost)) > 0 {
  298. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  299. cfg.Section("mailer").Key("HOST").SetValue(f.SMTPHost)
  300. cfg.Section("mailer").Key("FROM").SetValue(f.SMTPFrom)
  301. cfg.Section("mailer").Key("USER").SetValue(f.SMTPUser)
  302. cfg.Section("mailer").Key("PASSWD").SetValue(f.SMTPPasswd)
  303. } else {
  304. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  305. }
  306. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(f.RegisterConfirm))
  307. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(f.MailNotify))
  308. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(f.OfflineMode))
  309. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(f.DisableGravatar))
  310. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(f.EnableFederatedAvatar))
  311. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(f.DisableRegistration))
  312. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(f.EnableCaptcha))
  313. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(f.RequireSignInView))
  314. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  315. cfg.Section("session").Key("PROVIDER").SetValue("file")
  316. mode := "file"
  317. if f.EnableConsoleMode {
  318. mode = "console, file"
  319. }
  320. cfg.Section("log").Key("MODE").SetValue(mode)
  321. cfg.Section("log").Key("LEVEL").SetValue("Info")
  322. cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath)
  323. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  324. secretKey, err := tool.RandomString(15)
  325. if err != nil {
  326. c.RenderWithErr(c.Tr("install.secret_key_failed", err), INSTALL, &f)
  327. return
  328. }
  329. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  330. _ = os.MkdirAll(filepath.Dir(conf.CustomConf), os.ModePerm)
  331. if err := cfg.SaveTo(conf.CustomConf); err != nil {
  332. c.RenderWithErr(c.Tr("install.save_config_failed", err), INSTALL, &f)
  333. return
  334. }
  335. // NOTE: We reuse the current value because this handler does not have access to CLI flags.
  336. err = GlobalInit(conf.CustomConf)
  337. if err != nil {
  338. c.RenderWithErr(c.Tr("install.init_failed", err), INSTALL, &f)
  339. return
  340. }
  341. // Create admin account
  342. if len(f.AdminName) > 0 {
  343. u := &db.User{
  344. Name: f.AdminName,
  345. Email: f.AdminEmail,
  346. Passwd: f.AdminPasswd,
  347. IsAdmin: true,
  348. IsActive: true,
  349. }
  350. if err := db.CreateUser(u); err != nil {
  351. if !db.IsErrUserAlreadyExist(err) {
  352. conf.Security.InstallLock = false
  353. c.FormErr("AdminName", "AdminEmail")
  354. c.RenderWithErr(c.Tr("install.invalid_admin_setting", err), INSTALL, &f)
  355. return
  356. }
  357. log.Info("Admin account already exist")
  358. u, _ = db.GetUserByName(u.Name)
  359. }
  360. // Auto-login for admin
  361. c.Session.Set("uid", u.ID)
  362. c.Session.Set("uname", u.Name)
  363. }
  364. log.Info("First-time run install finished!")
  365. c.Flash.Success(c.Tr("install.install_success"))
  366. c.Redirect(f.AppUrl + "user/login")
  367. }