setting.go 19 KB

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