setting.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. _ "github.com/go-macaron/cache/memcache"
  17. _ "github.com/go-macaron/cache/redis"
  18. "github.com/go-macaron/session"
  19. _ "github.com/go-macaron/session/redis"
  20. "gopkg.in/ini.v1"
  21. "github.com/gogits/gogs/modules/bindata"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/user"
  24. )
  25. type Scheme string
  26. const (
  27. HTTP Scheme = "http"
  28. HTTPS Scheme = "https"
  29. FCGI Scheme = "fcgi"
  30. )
  31. type LandingPage string
  32. const (
  33. LANDING_PAGE_HOME LandingPage = "/"
  34. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  35. )
  36. var (
  37. // Build information.
  38. BuildTime string
  39. BuildGitHash string
  40. // App settings.
  41. AppVer string
  42. AppName string
  43. AppUrl string
  44. AppSubUrl string
  45. AppPath string
  46. AppDataPath = "data"
  47. // Server settings.
  48. Protocol Scheme
  49. Domain string
  50. HttpAddr, HttpPort string
  51. LocalUrl string
  52. DisableSSH bool
  53. StartSSHServer bool
  54. SSHDomain string
  55. SSHPort int
  56. OfflineMode bool
  57. DisableRouterLog bool
  58. CertFile, KeyFile string
  59. StaticRootPath string
  60. EnableGzip bool
  61. LandingPageUrl LandingPage
  62. // Security settings.
  63. InstallLock bool
  64. SecretKey string
  65. LogInRememberDays int
  66. CookieUserName string
  67. CookieRememberName string
  68. ReverseProxyAuthUser string
  69. // Database settings.
  70. UseSQLite3 bool
  71. UseMySQL bool
  72. UsePostgreSQL bool
  73. UseTiDB bool
  74. // Webhook settings.
  75. Webhook struct {
  76. QueueLength int
  77. DeliverTimeout int
  78. SkipTLSVerify bool
  79. Types []string
  80. PagingNum int
  81. }
  82. // Repository settings.
  83. Repository struct {
  84. AnsiCharset string
  85. ForcePrivate bool
  86. MaxCreationLimit int
  87. PullRequestQueueLength int
  88. }
  89. RepoRootPath string
  90. ScriptType string
  91. // UI settings.
  92. ExplorePagingNum int
  93. IssuePagingNum int
  94. FeedMaxCommitNum int
  95. AdminUserPagingNum int
  96. AdminRepoPagingNum int
  97. AdminNoticePagingNum int
  98. AdminOrgPagingNum int
  99. // Markdown sttings.
  100. Markdown struct {
  101. EnableHardLineBreak bool
  102. }
  103. // Picture settings.
  104. PictureService string
  105. AvatarUploadPath string
  106. GravatarSource string
  107. DisableGravatar bool
  108. // Log settings.
  109. LogRootPath string
  110. LogModes []string
  111. LogConfigs []string
  112. // Attachment settings.
  113. AttachmentPath string
  114. AttachmentAllowedTypes string
  115. AttachmentMaxSize int64
  116. AttachmentMaxFiles int
  117. AttachmentEnabled bool
  118. // Time settings.
  119. TimeFormat string
  120. // Cache settings.
  121. CacheAdapter string
  122. CacheInternal int
  123. CacheConn string
  124. // Session settings.
  125. SessionConfig session.Options
  126. // Git settings.
  127. Git struct {
  128. MaxGitDiffLines int
  129. GcArgs []string `delim:" "`
  130. }
  131. // Cron tasks.
  132. Cron struct {
  133. UpdateMirror struct {
  134. Enabled bool
  135. RunAtStart bool
  136. Schedule string
  137. } `ini:"cron.update_mirrors"`
  138. RepoHealthCheck struct {
  139. Enabled bool
  140. RunAtStart bool
  141. Schedule string
  142. Timeout time.Duration
  143. Args []string `delim:" "`
  144. } `ini:"cron.repo_health_check"`
  145. CheckRepoStats struct {
  146. Enabled bool
  147. RunAtStart bool
  148. Schedule string
  149. } `ini:"cron.check_repo_stats"`
  150. }
  151. // I18n settings.
  152. Langs, Names []string
  153. dateLangs map[string]string
  154. // Other settings.
  155. ShowFooterBranding bool
  156. ShowFooterVersion bool
  157. // Global setting objects.
  158. Cfg *ini.File
  159. CustomPath string // Custom directory path.
  160. CustomConf string
  161. ProdMode bool
  162. RunUser string
  163. IsWindows bool
  164. HasRobotsTxt bool
  165. )
  166. func DateLang(lang string) string {
  167. name, ok := dateLangs[lang]
  168. if ok {
  169. return name
  170. }
  171. return "en"
  172. }
  173. // execPath returns the executable path.
  174. func execPath() (string, error) {
  175. file, err := exec.LookPath(os.Args[0])
  176. if err != nil {
  177. return "", err
  178. }
  179. return filepath.Abs(file)
  180. }
  181. func init() {
  182. IsWindows = runtime.GOOS == "windows"
  183. log.NewLogger(0, "console", `{"level": 0}`)
  184. var err error
  185. if AppPath, err = execPath(); err != nil {
  186. log.Fatal(4, "fail to get app path: %v\n", err)
  187. }
  188. // Note: we don't use path.Dir here because it does not handle case
  189. // which path starts with two "/" in Windows: "//psf/Home/..."
  190. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  191. }
  192. // WorkDir returns absolute path of work directory.
  193. func WorkDir() (string, error) {
  194. wd := os.Getenv("GOGS_WORK_DIR")
  195. if len(wd) > 0 {
  196. return wd, nil
  197. }
  198. i := strings.LastIndex(AppPath, "/")
  199. if i == -1 {
  200. return AppPath, nil
  201. }
  202. return AppPath[:i], nil
  203. }
  204. func forcePathSeparator(path string) {
  205. if strings.Contains(path, "\\") {
  206. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  207. }
  208. }
  209. // NewContext initializes configuration context.
  210. // NOTE: do not print any log except error.
  211. func NewContext() {
  212. workDir, err := WorkDir()
  213. if err != nil {
  214. log.Fatal(4, "Fail to get work directory: %v", err)
  215. }
  216. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  217. if err != nil {
  218. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  219. }
  220. CustomPath = os.Getenv("GOGS_CUSTOM")
  221. if len(CustomPath) == 0 {
  222. CustomPath = workDir + "/custom"
  223. }
  224. if len(CustomConf) == 0 {
  225. CustomConf = CustomPath + "/conf/app.ini"
  226. }
  227. if com.IsFile(CustomConf) {
  228. if err = Cfg.Append(CustomConf); err != nil {
  229. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  230. }
  231. } else {
  232. log.Warn("Custom config (%s) not found, ignore this if you're running first time", CustomConf)
  233. }
  234. Cfg.NameMapper = ini.AllCapsUnderscore
  235. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  236. forcePathSeparator(LogRootPath)
  237. sec := Cfg.Section("server")
  238. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  239. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  240. if AppUrl[len(AppUrl)-1] != '/' {
  241. AppUrl += "/"
  242. }
  243. // Check if has app suburl.
  244. url, err := url.Parse(AppUrl)
  245. if err != nil {
  246. log.Fatal(4, "Invalid ROOT_URL(%s): %s", AppUrl, err)
  247. }
  248. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  249. Protocol = HTTP
  250. if sec.Key("PROTOCOL").String() == "https" {
  251. Protocol = HTTPS
  252. CertFile = sec.Key("CERT_FILE").String()
  253. KeyFile = sec.Key("KEY_FILE").String()
  254. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  255. Protocol = FCGI
  256. }
  257. Domain = sec.Key("DOMAIN").MustString("localhost")
  258. HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  259. HttpPort = sec.Key("HTTP_PORT").MustString("3000")
  260. LocalUrl = sec.Key("LOCAL_ROOT_URL").MustString("http://localhost:" + HttpPort + "/")
  261. DisableSSH = sec.Key("DISABLE_SSH").MustBool()
  262. if !DisableSSH {
  263. StartSSHServer = sec.Key("START_SSH_SERVER").MustBool()
  264. }
  265. SSHDomain = sec.Key("SSH_DOMAIN").MustString(Domain)
  266. SSHPort = sec.Key("SSH_PORT").MustInt(22)
  267. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  268. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  269. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  270. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  271. switch sec.Key("LANDING_PAGE").MustString("home") {
  272. case "explore":
  273. LandingPageUrl = LANDING_PAGE_EXPLORE
  274. default:
  275. LandingPageUrl = LANDING_PAGE_HOME
  276. }
  277. sec = Cfg.Section("security")
  278. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  279. SecretKey = sec.Key("SECRET_KEY").String()
  280. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  281. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  282. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  283. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  284. sec = Cfg.Section("attachment")
  285. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  286. if !filepath.IsAbs(AttachmentPath) {
  287. AttachmentPath = path.Join(workDir, AttachmentPath)
  288. }
  289. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  290. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  291. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  292. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  293. TimeFormat = map[string]string{
  294. "ANSIC": time.ANSIC,
  295. "UnixDate": time.UnixDate,
  296. "RubyDate": time.RubyDate,
  297. "RFC822": time.RFC822,
  298. "RFC822Z": time.RFC822Z,
  299. "RFC850": time.RFC850,
  300. "RFC1123": time.RFC1123,
  301. "RFC1123Z": time.RFC1123Z,
  302. "RFC3339": time.RFC3339,
  303. "RFC3339Nano": time.RFC3339Nano,
  304. "Kitchen": time.Kitchen,
  305. "Stamp": time.Stamp,
  306. "StampMilli": time.StampMilli,
  307. "StampMicro": time.StampMicro,
  308. "StampNano": time.StampNano,
  309. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  310. RunUser = Cfg.Section("").Key("RUN_USER").String()
  311. curUser := user.CurrentUsername()
  312. // Does not check run user when the install lock is off.
  313. if InstallLock && RunUser != curUser {
  314. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  315. }
  316. // Determine and create root git repository path.
  317. homeDir, err := com.HomeDir()
  318. if err != nil {
  319. log.Fatal(4, "Fail to get home directory: %v", err)
  320. }
  321. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  322. sec = Cfg.Section("repository")
  323. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  324. forcePathSeparator(RepoRootPath)
  325. if !filepath.IsAbs(RepoRootPath) {
  326. RepoRootPath = path.Join(workDir, RepoRootPath)
  327. } else {
  328. RepoRootPath = path.Clean(RepoRootPath)
  329. }
  330. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  331. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  332. log.Fatal(4, "Fail to map Repository settings: %v", err)
  333. }
  334. // UI settings.
  335. sec = Cfg.Section("ui")
  336. ExplorePagingNum = sec.Key("EXPLORE_PAGING_NUM").MustInt(20)
  337. IssuePagingNum = sec.Key("ISSUE_PAGING_NUM").MustInt(10)
  338. FeedMaxCommitNum = sec.Key("FEED_MAX_COMMIT_NUM").MustInt(5)
  339. sec = Cfg.Section("ui.admin")
  340. AdminUserPagingNum = sec.Key("USER_PAGING_NUM").MustInt(50)
  341. AdminRepoPagingNum = sec.Key("REPO_PAGING_NUM").MustInt(50)
  342. AdminNoticePagingNum = sec.Key("NOTICE_PAGING_NUM").MustInt(50)
  343. AdminOrgPagingNum = sec.Key("ORG_PAGING_NUM").MustInt(50)
  344. sec = Cfg.Section("picture")
  345. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  346. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  347. forcePathSeparator(AvatarUploadPath)
  348. if !filepath.IsAbs(AvatarUploadPath) {
  349. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  350. }
  351. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  352. case "duoshuo":
  353. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  354. case "gravatar":
  355. GravatarSource = "//1.gravatar.com/avatar/"
  356. default:
  357. GravatarSource = source
  358. }
  359. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  360. if OfflineMode {
  361. DisableGravatar = true
  362. }
  363. if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  364. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  365. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  366. log.Fatal(4, "Fail to map Git settings: %v", err)
  367. } else if Cfg.Section("cron").MapTo(&Cron); err != nil {
  368. log.Fatal(4, "Fail to map Cron settings: %v", err)
  369. }
  370. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  371. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  372. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  373. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  374. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  375. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  376. }
  377. var Service struct {
  378. ActiveCodeLives int
  379. ResetPwdCodeLives int
  380. RegisterEmailConfirm bool
  381. DisableRegistration bool
  382. ShowRegistrationButton bool
  383. RequireSignInView bool
  384. EnableCacheAvatar bool
  385. EnableNotifyMail bool
  386. EnableReverseProxyAuth bool
  387. EnableReverseProxyAutoRegister bool
  388. DisableMinimumKeySizeCheck bool
  389. MinimumKeySizes map[string]int
  390. EnableCaptcha bool
  391. }
  392. func newService() {
  393. sec := Cfg.Section("service")
  394. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  395. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  396. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  397. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  398. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  399. Service.EnableCacheAvatar = sec.Key("ENABLE_CACHE_AVATAR").MustBool()
  400. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  401. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  402. Service.DisableMinimumKeySizeCheck = sec.Key("DISABLE_MINIMUM_KEY_SIZE_CHECK").MustBool()
  403. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  404. minimumKeySizes := Cfg.Section("service.minimum_key_sizes").Keys()
  405. Service.MinimumKeySizes = make(map[string]int)
  406. for _, key := range minimumKeySizes {
  407. Service.MinimumKeySizes[key.Name()] = key.MustInt()
  408. }
  409. }
  410. var logLevels = map[string]string{
  411. "Trace": "0",
  412. "Debug": "1",
  413. "Info": "2",
  414. "Warn": "3",
  415. "Error": "4",
  416. "Critical": "5",
  417. }
  418. func newLogService() {
  419. log.Info("%s %s", AppName, AppVer)
  420. if len(BuildTime) > 0 {
  421. log.Info("Build Time: %s", BuildTime)
  422. log.Info("Build Git Hash: %s", BuildGitHash)
  423. }
  424. // Get and check log mode.
  425. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  426. LogConfigs = make([]string, len(LogModes))
  427. for i, mode := range LogModes {
  428. mode = strings.TrimSpace(mode)
  429. sec, err := Cfg.GetSection("log." + mode)
  430. if err != nil {
  431. log.Fatal(4, "Unknown log mode: %s", mode)
  432. }
  433. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  434. // Log level.
  435. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  436. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  437. validLevels)
  438. level, ok := logLevels[levelName]
  439. if !ok {
  440. log.Fatal(4, "Unknown log level: %s", levelName)
  441. }
  442. // Generate log configuration.
  443. switch mode {
  444. case "console":
  445. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  446. case "file":
  447. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  448. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  449. panic(err.Error())
  450. }
  451. LogConfigs[i] = fmt.Sprintf(
  452. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  453. logPath,
  454. sec.Key("LOG_ROTATE").MustBool(true),
  455. sec.Key("MAX_LINES").MustInt(1000000),
  456. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  457. sec.Key("DAILY_ROTATE").MustBool(true),
  458. sec.Key("MAX_DAYS").MustInt(7))
  459. case "conn":
  460. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  461. sec.Key("RECONNECT_ON_MSG").MustBool(),
  462. sec.Key("RECONNECT").MustBool(),
  463. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  464. sec.Key("ADDR").MustString(":7020"))
  465. case "smtp":
  466. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  467. sec.Key("USER").MustString("example@example.com"),
  468. sec.Key("PASSWD").MustString("******"),
  469. sec.Key("HOST").MustString("127.0.0.1:25"),
  470. sec.Key("RECEIVERS").MustString("[]"),
  471. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  472. case "database":
  473. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  474. sec.Key("DRIVER").String(),
  475. sec.Key("CONN").String())
  476. }
  477. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  478. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  479. }
  480. }
  481. func newCacheService() {
  482. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  483. switch CacheAdapter {
  484. case "memory":
  485. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  486. case "redis", "memcache":
  487. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  488. default:
  489. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  490. }
  491. log.Info("Cache Service Enabled")
  492. }
  493. func newSessionService() {
  494. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  495. []string{"memory", "file", "redis", "mysql"})
  496. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  497. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  498. SessionConfig.CookiePath = AppSubUrl
  499. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  500. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  501. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  502. log.Info("Session Service Enabled")
  503. }
  504. // Mailer represents mail service.
  505. type Mailer struct {
  506. QueueLength int
  507. Name string
  508. Host string
  509. From string
  510. User, Passwd string
  511. DisableHelo bool
  512. HeloHostname string
  513. SkipVerify bool
  514. UseCertificate bool
  515. CertFile, KeyFile string
  516. }
  517. var (
  518. MailService *Mailer
  519. )
  520. func newMailService() {
  521. sec := Cfg.Section("mailer")
  522. // Check mailer setting.
  523. if !sec.Key("ENABLED").MustBool() {
  524. return
  525. }
  526. MailService = &Mailer{
  527. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  528. Name: sec.Key("NAME").MustString(AppName),
  529. Host: sec.Key("HOST").String(),
  530. User: sec.Key("USER").String(),
  531. Passwd: sec.Key("PASSWD").String(),
  532. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  533. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  534. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  535. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  536. CertFile: sec.Key("CERT_FILE").String(),
  537. KeyFile: sec.Key("KEY_FILE").String(),
  538. }
  539. MailService.From = sec.Key("FROM").MustString(MailService.User)
  540. log.Info("Mail Service Enabled")
  541. }
  542. func newRegisterMailService() {
  543. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  544. return
  545. } else if MailService == nil {
  546. log.Warn("Register Mail Service: Mail Service is not enabled")
  547. return
  548. }
  549. Service.RegisterEmailConfirm = true
  550. log.Info("Register Mail Service Enabled")
  551. }
  552. func newNotifyMailService() {
  553. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  554. return
  555. } else if MailService == nil {
  556. log.Warn("Notify Mail Service: Mail Service is not enabled")
  557. return
  558. }
  559. Service.EnableNotifyMail = true
  560. log.Info("Notify Mail Service Enabled")
  561. }
  562. func newWebhookService() {
  563. sec := Cfg.Section("webhook")
  564. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  565. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  566. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  567. Webhook.Types = []string{"gogs", "slack"}
  568. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  569. }
  570. func NewServices() {
  571. newService()
  572. newLogService()
  573. newCacheService()
  574. newSessionService()
  575. newMailService()
  576. newRegisterMailService()
  577. newNotifyMailService()
  578. newWebhookService()
  579. }