1
0

install.go 12 KB

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