install.go 12 KB

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