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

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