setting.go 19 KB

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