setting.go 24 KB

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