setting.go 19 KB

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