You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 setting
  5. import (
  6. "fmt"
  7. "net/mail"
  8. "net/url"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. _ "github.com/go-macaron/cache/memcache"
  19. _ "github.com/go-macaron/cache/redis"
  20. "github.com/go-macaron/session"
  21. _ "github.com/go-macaron/session/redis"
  22. "gopkg.in/ini.v1"
  23. "strk.kbt.io/projects/go/libravatar"
  24. "github.com/go-gitea/gitea/modules/bindata"
  25. "github.com/go-gitea/gitea/modules/log"
  26. "github.com/go-gitea/gitea/modules/user"
  27. )
  28. type Scheme string
  29. const (
  30. HTTP Scheme = "http"
  31. HTTPS Scheme = "https"
  32. FCGI Scheme = "fcgi"
  33. UNIX_SOCKET Scheme = "unix"
  34. )
  35. type LandingPage string
  36. const (
  37. LANDING_PAGE_HOME LandingPage = "/"
  38. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  39. )
  40. var (
  41. // Build information should only be set by -ldflags.
  42. BuildTime string
  43. BuildGitHash string
  44. // App settings
  45. AppVer string
  46. AppName string
  47. AppUrl string
  48. AppSubUrl string
  49. AppSubUrlDepth int // Number of slashes
  50. AppPath string
  51. AppDataPath string
  52. // Server settings
  53. Protocol Scheme
  54. Domain string
  55. HTTPAddr, HTTPPort string
  56. LocalURL string
  57. OfflineMode bool
  58. DisableRouterLog bool
  59. CertFile, KeyFile string
  60. StaticRootPath string
  61. EnableGzip bool
  62. LandingPageURL LandingPage
  63. UnixSocketPermission uint32
  64. SSH struct {
  65. Disabled bool `ini:"DISABLE_SSH"`
  66. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  67. Domain string `ini:"SSH_DOMAIN"`
  68. Port int `ini:"SSH_PORT"`
  69. ListenPort int `ini:"SSH_LISTEN_PORT"`
  70. RootPath string `ini:"SSH_ROOT_PATH"`
  71. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  72. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  73. MinimumKeySizeCheck bool `ini:"-"`
  74. MinimumKeySizes map[string]int `ini:"-"`
  75. }
  76. // Security settings
  77. InstallLock bool
  78. SecretKey string
  79. LogInRememberDays int
  80. CookieUserName string
  81. CookieRememberName string
  82. ReverseProxyAuthUser string
  83. // Database settings
  84. UseSQLite3 bool
  85. UseMySQL bool
  86. UsePostgreSQL bool
  87. UseTiDB bool
  88. // Webhook settings
  89. Webhook struct {
  90. QueueLength int
  91. DeliverTimeout int
  92. SkipTLSVerify bool
  93. Types []string
  94. PagingNum int
  95. }
  96. // Repository settings
  97. Repository struct {
  98. AnsiCharset string
  99. ForcePrivate bool
  100. MaxCreationLimit int
  101. MirrorQueueLength int
  102. PullRequestQueueLength int
  103. PreferredLicenses []string
  104. // Repository editor settings
  105. Editor struct {
  106. LineWrapExtensions []string
  107. PreviewableFileModes []string
  108. } `ini:"-"`
  109. // Repository upload settings
  110. Upload struct {
  111. Enabled bool
  112. TempPath string
  113. AllowedTypes []string `delim:"|"`
  114. FileMaxSize int64
  115. MaxFiles int
  116. } `ini:"-"`
  117. }
  118. RepoRootPath string
  119. ScriptType string
  120. // UI settings
  121. UI struct {
  122. ExplorePagingNum int
  123. IssuePagingNum int
  124. FeedMaxCommitNum int
  125. ThemeColorMetaTag string
  126. MaxDisplayFileSize int64
  127. Admin struct {
  128. UserPagingNum int
  129. RepoPagingNum int
  130. NoticePagingNum int
  131. OrgPagingNum int
  132. } `ini:"ui.admin"`
  133. User struct {
  134. RepoPagingNum int
  135. } `ini:"ui.user"`
  136. }
  137. // Markdown sttings
  138. Markdown struct {
  139. EnableHardLineBreak bool
  140. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  141. FileExtensions []string
  142. }
  143. // Picture settings
  144. AvatarUploadPath string
  145. GravatarSource string
  146. DisableGravatar bool
  147. EnableFederatedAvatar bool
  148. LibravatarService *libravatar.Libravatar
  149. // Log settings
  150. LogRootPath string
  151. LogModes []string
  152. LogConfigs []string
  153. // Attachment settings
  154. AttachmentPath string
  155. AttachmentAllowedTypes string
  156. AttachmentMaxSize int64
  157. AttachmentMaxFiles int
  158. AttachmentEnabled bool
  159. // Time settings
  160. TimeFormat string
  161. // Cache settings
  162. CacheAdapter string
  163. CacheInterval int
  164. CacheConn string
  165. // Session settings
  166. SessionConfig session.Options
  167. CSRFCookieName = "_csrf"
  168. // Cron tasks
  169. Cron struct {
  170. UpdateMirror struct {
  171. Enabled bool
  172. RunAtStart bool
  173. Schedule string
  174. } `ini:"cron.update_mirrors"`
  175. RepoHealthCheck struct {
  176. Enabled bool
  177. RunAtStart bool
  178. Schedule string
  179. Timeout time.Duration
  180. Args []string `delim:" "`
  181. } `ini:"cron.repo_health_check"`
  182. CheckRepoStats struct {
  183. Enabled bool
  184. RunAtStart bool
  185. Schedule string
  186. } `ini:"cron.check_repo_stats"`
  187. }
  188. // Git settings
  189. Git struct {
  190. DisableDiffHighlight bool
  191. MaxGitDiffLines int
  192. MaxGitDiffLineCharacters int
  193. MaxGitDiffFiles int
  194. GCArgs []string `delim:" "`
  195. Timeout struct {
  196. Migrate int
  197. Mirror int
  198. Clone int
  199. Pull int
  200. GC int `ini:"GC"`
  201. } `ini:"git.timeout"`
  202. }
  203. // Mirror settings
  204. Mirror struct {
  205. DefaultInterval int
  206. }
  207. // API settings
  208. API struct {
  209. MaxResponseItems int
  210. }
  211. // I18n settings
  212. Langs, Names []string
  213. dateLangs map[string]string
  214. // Highlight settings are loaded in modules/template/hightlight.go
  215. // Other settings
  216. ShowFooterBranding bool
  217. ShowFooterVersion bool
  218. ShowFooterTemplateLoadTime bool
  219. SupportMiniWinService bool
  220. // Global setting objects
  221. Cfg *ini.File
  222. CustomPath string // Custom directory path
  223. CustomConf string
  224. ProdMode bool
  225. RunUser string
  226. IsWindows bool
  227. HasRobotsTxt bool
  228. )
  229. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  230. func DateLang(lang string) string {
  231. name, ok := dateLangs[lang]
  232. if ok {
  233. return name
  234. }
  235. return "en"
  236. }
  237. // execPath returns the executable path.
  238. func execPath() (string, error) {
  239. file, err := exec.LookPath(os.Args[0])
  240. if err != nil {
  241. return "", err
  242. }
  243. return filepath.Abs(file)
  244. }
  245. func init() {
  246. IsWindows = runtime.GOOS == "windows"
  247. log.NewLogger(0, "console", `{"level": 0}`)
  248. var err error
  249. if AppPath, err = execPath(); err != nil {
  250. log.Fatal(4, "fail to get app path: %v\n", err)
  251. }
  252. // Note: we don't use path.Dir here because it does not handle case
  253. // which path starts with two "/" in Windows: "//psf/Home/..."
  254. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  255. }
  256. // WorkDir returns absolute path of work directory.
  257. func WorkDir() (string, error) {
  258. wd := os.Getenv("GOGS_WORK_DIR")
  259. if len(wd) > 0 {
  260. return wd, nil
  261. }
  262. i := strings.LastIndex(AppPath, "/")
  263. if i == -1 {
  264. return AppPath, nil
  265. }
  266. return AppPath[:i], nil
  267. }
  268. func forcePathSeparator(path string) {
  269. if strings.Contains(path, "\\") {
  270. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  271. }
  272. }
  273. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  274. // actual user that runs the app. The first return value is the actual user name.
  275. // This check is ignored under Windows since SSH remote login is not the main
  276. // method to login on Windows.
  277. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  278. if IsWindows {
  279. return "", true
  280. }
  281. currentUser := user.CurrentUsername()
  282. return currentUser, runUser == currentUser
  283. }
  284. // NewContext initializes configuration context.
  285. // NOTE: do not print any log except error.
  286. func NewContext() {
  287. workDir, err := WorkDir()
  288. if err != nil {
  289. log.Fatal(4, "Fail to get work directory: %v", err)
  290. }
  291. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  292. if err != nil {
  293. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  294. }
  295. CustomPath = os.Getenv("GOGS_CUSTOM")
  296. if len(CustomPath) == 0 {
  297. CustomPath = workDir + "/custom"
  298. }
  299. if len(CustomConf) == 0 {
  300. CustomConf = CustomPath + "/conf/app.ini"
  301. }
  302. if com.IsFile(CustomConf) {
  303. if err = Cfg.Append(CustomConf); err != nil {
  304. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  305. }
  306. } else {
  307. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  308. }
  309. Cfg.NameMapper = ini.AllCapsUnderscore
  310. homeDir, err := com.HomeDir()
  311. if err != nil {
  312. log.Fatal(4, "Fail to get home directory: %v", err)
  313. }
  314. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  315. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  316. forcePathSeparator(LogRootPath)
  317. sec := Cfg.Section("server")
  318. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  319. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  320. if AppUrl[len(AppUrl)-1] != '/' {
  321. AppUrl += "/"
  322. }
  323. // Check if has app suburl.
  324. url, err := url.Parse(AppUrl)
  325. if err != nil {
  326. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
  327. }
  328. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  329. // This value is empty if site does not have sub-url.
  330. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  331. AppSubUrlDepth = strings.Count(AppSubUrl, "/")
  332. Protocol = HTTP
  333. if sec.Key("PROTOCOL").String() == "https" {
  334. Protocol = HTTPS
  335. CertFile = sec.Key("CERT_FILE").String()
  336. KeyFile = sec.Key("KEY_FILE").String()
  337. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  338. Protocol = FCGI
  339. } else if sec.Key("PROTOCOL").String() == "unix" {
  340. Protocol = UNIX_SOCKET
  341. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  342. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  343. if err != nil || UnixSocketPermissionParsed > 0777 {
  344. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  345. }
  346. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  347. }
  348. Domain = sec.Key("DOMAIN").MustString("localhost")
  349. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  350. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  351. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  352. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  353. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  354. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  355. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  356. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  357. switch sec.Key("LANDING_PAGE").MustString("home") {
  358. case "explore":
  359. LandingPageURL = LANDING_PAGE_EXPLORE
  360. default:
  361. LandingPageURL = LANDING_PAGE_HOME
  362. }
  363. SSH.RootPath = path.Join(homeDir, ".ssh")
  364. SSH.KeyTestPath = os.TempDir()
  365. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  366. log.Fatal(4, "Fail to map SSH settings: %v", err)
  367. }
  368. // When disable SSH, start builtin server value is ignored.
  369. if SSH.Disabled {
  370. SSH.StartBuiltinServer = false
  371. }
  372. if !SSH.Disabled && !SSH.StartBuiltinServer {
  373. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  374. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  375. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  376. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  377. }
  378. }
  379. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  380. SSH.MinimumKeySizes = map[string]int{}
  381. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  382. for _, key := range minimumKeySizes {
  383. if key.MustInt() != -1 {
  384. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  385. }
  386. }
  387. sec = Cfg.Section("security")
  388. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  389. SecretKey = sec.Key("SECRET_KEY").String()
  390. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  391. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  392. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  393. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  394. sec = Cfg.Section("attachment")
  395. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  396. if !filepath.IsAbs(AttachmentPath) {
  397. AttachmentPath = path.Join(workDir, AttachmentPath)
  398. }
  399. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  400. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  401. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  402. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  403. TimeFormat = map[string]string{
  404. "ANSIC": time.ANSIC,
  405. "UnixDate": time.UnixDate,
  406. "RubyDate": time.RubyDate,
  407. "RFC822": time.RFC822,
  408. "RFC822Z": time.RFC822Z,
  409. "RFC850": time.RFC850,
  410. "RFC1123": time.RFC1123,
  411. "RFC1123Z": time.RFC1123Z,
  412. "RFC3339": time.RFC3339,
  413. "RFC3339Nano": time.RFC3339Nano,
  414. "Kitchen": time.Kitchen,
  415. "Stamp": time.Stamp,
  416. "StampMilli": time.StampMilli,
  417. "StampMicro": time.StampMicro,
  418. "StampNano": time.StampNano,
  419. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  420. RunUser = Cfg.Section("").Key("RUN_USER").String()
  421. // Does not check run user when the install lock is off.
  422. if InstallLock {
  423. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  424. if !match {
  425. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  426. }
  427. }
  428. // Determine and create root git repository path.
  429. sec = Cfg.Section("repository")
  430. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  431. forcePathSeparator(RepoRootPath)
  432. if !filepath.IsAbs(RepoRootPath) {
  433. RepoRootPath = path.Join(workDir, RepoRootPath)
  434. } else {
  435. RepoRootPath = path.Clean(RepoRootPath)
  436. }
  437. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  438. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  439. log.Fatal(4, "Fail to map Repository settings: %v", err)
  440. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  441. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  442. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  443. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  444. }
  445. if !filepath.IsAbs(Repository.Upload.TempPath) {
  446. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  447. }
  448. sec = Cfg.Section("picture")
  449. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  450. forcePathSeparator(AvatarUploadPath)
  451. if !filepath.IsAbs(AvatarUploadPath) {
  452. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  453. }
  454. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  455. case "duoshuo":
  456. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  457. case "gravatar":
  458. GravatarSource = "https://secure.gravatar.com/avatar/"
  459. default:
  460. GravatarSource = source
  461. }
  462. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  463. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  464. if OfflineMode {
  465. DisableGravatar = true
  466. EnableFederatedAvatar = false
  467. }
  468. if DisableGravatar {
  469. EnableFederatedAvatar = false
  470. }
  471. if EnableFederatedAvatar {
  472. LibravatarService = libravatar.New()
  473. parts := strings.Split(GravatarSource, "/")
  474. if len(parts) >= 3 {
  475. if parts[0] == "https:" {
  476. LibravatarService.SetUseHTTPS(true)
  477. LibravatarService.SetSecureFallbackHost(parts[2])
  478. } else {
  479. LibravatarService.SetUseHTTPS(false)
  480. LibravatarService.SetFallbackHost(parts[2])
  481. }
  482. }
  483. }
  484. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  485. log.Fatal(4, "Fail to map UI settings: %v", err)
  486. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  487. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  488. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  489. log.Fatal(4, "Fail to map Cron settings: %v", err)
  490. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  491. log.Fatal(4, "Fail to map Git settings: %v", err)
  492. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  493. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  494. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  495. log.Fatal(4, "Fail to map API settings: %v", err)
  496. }
  497. if Mirror.DefaultInterval <= 0 {
  498. Mirror.DefaultInterval = 24
  499. }
  500. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  501. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  502. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  503. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  504. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  505. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  506. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  507. }
  508. var Service struct {
  509. ActiveCodeLives int
  510. ResetPwdCodeLives int
  511. RegisterEmailConfirm bool
  512. DisableRegistration bool
  513. ShowRegistrationButton bool
  514. RequireSignInView bool
  515. EnableNotifyMail bool
  516. EnableReverseProxyAuth bool
  517. EnableReverseProxyAutoRegister bool
  518. EnableCaptcha bool
  519. }
  520. func newService() {
  521. sec := Cfg.Section("service")
  522. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  523. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  524. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  525. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  526. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  527. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  528. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  529. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  530. }
  531. var logLevels = map[string]string{
  532. "Trace": "0",
  533. "Debug": "1",
  534. "Info": "2",
  535. "Warn": "3",
  536. "Error": "4",
  537. "Critical": "5",
  538. }
  539. func newLogService() {
  540. log.Info("%s %s", AppName, AppVer)
  541. if len(BuildTime) > 0 {
  542. log.Info("Build Time: %s", BuildTime)
  543. log.Info("Build Git Hash: %s", BuildGitHash)
  544. }
  545. // Get and check log mode.
  546. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  547. LogConfigs = make([]string, len(LogModes))
  548. for i, mode := range LogModes {
  549. mode = strings.TrimSpace(mode)
  550. sec, err := Cfg.GetSection("log." + mode)
  551. if err != nil {
  552. log.Fatal(4, "Unknown log mode: %s", mode)
  553. }
  554. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  555. // Log level.
  556. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  557. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  558. validLevels)
  559. level, ok := logLevels[levelName]
  560. if !ok {
  561. log.Fatal(4, "Unknown log level: %s", levelName)
  562. }
  563. // Generate log configuration.
  564. switch mode {
  565. case "console":
  566. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  567. case "file":
  568. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  569. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  570. panic(err.Error())
  571. }
  572. LogConfigs[i] = fmt.Sprintf(
  573. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  574. logPath,
  575. sec.Key("LOG_ROTATE").MustBool(true),
  576. sec.Key("MAX_LINES").MustInt(1000000),
  577. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  578. sec.Key("DAILY_ROTATE").MustBool(true),
  579. sec.Key("MAX_DAYS").MustInt(7))
  580. case "conn":
  581. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  582. sec.Key("RECONNECT_ON_MSG").MustBool(),
  583. sec.Key("RECONNECT").MustBool(),
  584. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  585. sec.Key("ADDR").MustString(":7020"))
  586. case "smtp":
  587. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  588. sec.Key("USER").MustString("example@example.com"),
  589. sec.Key("PASSWD").MustString("******"),
  590. sec.Key("HOST").MustString("127.0.0.1:25"),
  591. sec.Key("RECEIVERS").MustString("[]"),
  592. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  593. case "database":
  594. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  595. sec.Key("DRIVER").String(),
  596. sec.Key("CONN").String())
  597. }
  598. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  599. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  600. }
  601. }
  602. func newCacheService() {
  603. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  604. switch CacheAdapter {
  605. case "memory":
  606. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  607. case "redis", "memcache":
  608. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  609. default:
  610. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  611. }
  612. log.Info("Cache Service Enabled")
  613. }
  614. func newSessionService() {
  615. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  616. []string{"memory", "file", "redis", "mysql"})
  617. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  618. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  619. SessionConfig.CookiePath = AppSubUrl
  620. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  621. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  622. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  623. log.Info("Session Service Enabled")
  624. }
  625. // Mailer represents mail service.
  626. type Mailer struct {
  627. QueueLength int
  628. Name string
  629. Host string
  630. From string
  631. FromEmail string
  632. User, Passwd string
  633. DisableHelo bool
  634. HeloHostname string
  635. SkipVerify bool
  636. UseCertificate bool
  637. CertFile, KeyFile string
  638. EnableHTMLAlternative bool
  639. }
  640. var (
  641. MailService *Mailer
  642. )
  643. func newMailService() {
  644. sec := Cfg.Section("mailer")
  645. // Check mailer setting.
  646. if !sec.Key("ENABLED").MustBool() {
  647. return
  648. }
  649. MailService = &Mailer{
  650. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  651. Name: sec.Key("NAME").MustString(AppName),
  652. Host: sec.Key("HOST").String(),
  653. User: sec.Key("USER").String(),
  654. Passwd: sec.Key("PASSWD").String(),
  655. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  656. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  657. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  658. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  659. CertFile: sec.Key("CERT_FILE").String(),
  660. KeyFile: sec.Key("KEY_FILE").String(),
  661. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  662. }
  663. MailService.From = sec.Key("FROM").MustString(MailService.User)
  664. parsed, err := mail.ParseAddress(MailService.From)
  665. if err != nil {
  666. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  667. }
  668. MailService.FromEmail = parsed.Address
  669. log.Info("Mail Service Enabled")
  670. }
  671. func newRegisterMailService() {
  672. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  673. return
  674. } else if MailService == nil {
  675. log.Warn("Register Mail Service: Mail Service is not enabled")
  676. return
  677. }
  678. Service.RegisterEmailConfirm = true
  679. log.Info("Register Mail Service Enabled")
  680. }
  681. func newNotifyMailService() {
  682. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  683. return
  684. } else if MailService == nil {
  685. log.Warn("Notify Mail Service: Mail Service is not enabled")
  686. return
  687. }
  688. Service.EnableNotifyMail = true
  689. log.Info("Notify Mail Service Enabled")
  690. }
  691. func newWebhookService() {
  692. sec := Cfg.Section("webhook")
  693. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  694. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  695. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  696. Webhook.Types = []string{"gogs", "slack"}
  697. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  698. }
  699. func NewServices() {
  700. newService()
  701. newLogService()
  702. newCacheService()
  703. newSessionService()
  704. newMailService()
  705. newRegisterMailService()
  706. newNotifyMailService()
  707. newWebhookService()
  708. }