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

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