1
0

install.go 13 KB

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