You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 19KB

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. 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. EnableCaptcha bool
  396. }
  397. func newService() {
  398. sec := Cfg.Section("service")
  399. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  400. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  401. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  402. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  403. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  404. Service.EnableCacheAvatar = sec.Key("ENABLE_CACHE_AVATAR").MustBool()
  405. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  406. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  407. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  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. }