install.go 12 KB

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