setting.go 19 KB

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