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 18KB

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