setting.go 22 KB

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