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

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