setting.go 19 KB

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