install.go 12 KB

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