setting.go 19 KB

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