setting.go 19 KB

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