1
0

install.go 12 KB

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