install.go 13 KB

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