setting.go 19 KB

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