setting.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. "net/mail"
  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/mcuadros/go-version"
  22. log "gopkg.in/clog.v1"
  23. "gopkg.in/ini.v1"
  24. "github.com/gogs/go-libravatar"
  25. "github.com/gogs/gogs/pkg/bindata"
  26. "github.com/gogs/gogs/pkg/process"
  27. "github.com/gogs/gogs/pkg/user"
  28. )
  29. type Scheme string
  30. const (
  31. SCHEME_HTTP Scheme = "http"
  32. SCHEME_HTTPS Scheme = "https"
  33. SCHEME_FCGI Scheme = "fcgi"
  34. SCHEME_UNIX_SOCKET Scheme = "unix"
  35. )
  36. type LandingPage string
  37. const (
  38. LANDING_PAGE_HOME LandingPage = "/"
  39. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  40. )
  41. var (
  42. // Build information should only be set by -ldflags.
  43. BuildTime string
  44. BuildGitHash string
  45. // App settings
  46. AppVer string
  47. AppName string
  48. AppURL string
  49. AppSubURL string
  50. AppSubURLDepth int // Number of slashes
  51. AppPath string
  52. AppDataPath string
  53. // Server settings
  54. Protocol Scheme
  55. Domain string
  56. HTTPAddr string
  57. HTTPPort string
  58. LocalURL string
  59. OfflineMode bool
  60. DisableRouterLog bool
  61. CertFile, KeyFile string
  62. TLSMinVersion string
  63. StaticRootPath string
  64. EnableGzip bool
  65. LandingPageURL LandingPage
  66. UnixSocketPermission uint32
  67. HTTP struct {
  68. AccessControlAllowOrigin string
  69. }
  70. SSH struct {
  71. Disabled bool `ini:"DISABLE_SSH"`
  72. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  73. Domain string `ini:"SSH_DOMAIN"`
  74. Port int `ini:"SSH_PORT"`
  75. ListenHost string `ini:"SSH_LISTEN_HOST"`
  76. ListenPort int `ini:"SSH_LISTEN_PORT"`
  77. RootPath string `ini:"SSH_ROOT_PATH"`
  78. RewriteAuthorizedKeysAtStart bool `ini:"REWRITE_AUTHORIZED_KEYS_AT_START"`
  79. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  80. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  81. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  82. MinimumKeySizeCheck bool `ini:"MINIMUM_KEY_SIZE_CHECK"`
  83. MinimumKeySizes map[string]int `ini:"-"`
  84. }
  85. // Security settings
  86. InstallLock bool
  87. SecretKey string
  88. LoginRememberDays int
  89. CookieUserName string
  90. CookieRememberName string
  91. CookieSecure bool
  92. ReverseProxyAuthUser string
  93. EnableLoginStatusCookie bool
  94. LoginStatusCookieName string
  95. // Database settings
  96. UseSQLite3 bool
  97. UseMySQL bool
  98. UsePostgreSQL bool
  99. UseMSSQL bool
  100. // Repository settings
  101. Repository struct {
  102. AnsiCharset string
  103. ForcePrivate bool
  104. MaxCreationLimit int
  105. MirrorQueueLength int
  106. PullRequestQueueLength int
  107. PreferredLicenses []string
  108. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  109. EnableLocalPathMigration bool
  110. CommitsFetchConcurrency int
  111. EnableRawFileRenderMode bool
  112. // Repository editor settings
  113. Editor struct {
  114. LineWrapExtensions []string
  115. PreviewableFileModes []string
  116. } `ini:"-"`
  117. // Repository upload settings
  118. Upload struct {
  119. Enabled bool
  120. TempPath string
  121. AllowedTypes []string `delim:"|"`
  122. FileMaxSize int64
  123. MaxFiles int
  124. } `ini:"-"`
  125. }
  126. RepoRootPath string
  127. ScriptType string
  128. // Webhook settings
  129. Webhook struct {
  130. Types []string
  131. QueueLength int
  132. DeliverTimeout int
  133. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  134. PagingNum int
  135. }
  136. // Release settigns
  137. Release struct {
  138. Attachment struct {
  139. Enabled bool
  140. TempPath string
  141. AllowedTypes []string `delim:"|"`
  142. MaxSize int64
  143. MaxFiles int
  144. } `ini:"-"`
  145. }
  146. // Markdown sttings
  147. Markdown struct {
  148. EnableHardLineBreak bool
  149. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  150. FileExtensions []string
  151. }
  152. // Smartypants settings
  153. Smartypants struct {
  154. Enabled bool
  155. Fractions bool
  156. Dashes bool
  157. LatexDashes bool
  158. AngledQuotes bool
  159. }
  160. // Admin settings
  161. Admin struct {
  162. DisableRegularOrgCreation bool
  163. }
  164. // Picture settings
  165. AvatarUploadPath string
  166. GravatarSource string
  167. DisableGravatar bool
  168. EnableFederatedAvatar bool
  169. LibravatarService *libravatar.Libravatar
  170. // Log settings
  171. LogRootPath string
  172. LogModes []string
  173. LogConfigs []interface{}
  174. // Attachment settings
  175. AttachmentPath string
  176. AttachmentAllowedTypes string
  177. AttachmentMaxSize int64
  178. AttachmentMaxFiles int
  179. AttachmentEnabled bool
  180. // Time settings
  181. TimeFormat string
  182. // Cache settings
  183. CacheAdapter string
  184. CacheInterval int
  185. CacheConn string
  186. // Session settings
  187. SessionConfig session.Options
  188. CSRFCookieName string
  189. // Cron tasks
  190. Cron struct {
  191. UpdateMirror struct {
  192. Enabled bool
  193. RunAtStart bool
  194. Schedule string
  195. } `ini:"cron.update_mirrors"`
  196. RepoHealthCheck struct {
  197. Enabled bool
  198. RunAtStart bool
  199. Schedule string
  200. Timeout time.Duration
  201. Args []string `delim:" "`
  202. } `ini:"cron.repo_health_check"`
  203. CheckRepoStats struct {
  204. Enabled bool
  205. RunAtStart bool
  206. Schedule string
  207. } `ini:"cron.check_repo_stats"`
  208. RepoArchiveCleanup struct {
  209. Enabled bool
  210. RunAtStart bool
  211. Schedule string
  212. OlderThan time.Duration
  213. } `ini:"cron.repo_archive_cleanup"`
  214. }
  215. // Git settings
  216. Git struct {
  217. Version string `ini:"-"`
  218. DisableDiffHighlight bool
  219. MaxGitDiffLines int
  220. MaxGitDiffLineCharacters int
  221. MaxGitDiffFiles int
  222. GCArgs []string `ini:"GC_ARGS" delim:" "`
  223. Timeout struct {
  224. Migrate int
  225. Mirror int
  226. Clone int
  227. Pull int
  228. GC int `ini:"GC"`
  229. } `ini:"git.timeout"`
  230. }
  231. // Mirror settings
  232. Mirror struct {
  233. DefaultInterval int
  234. }
  235. // API settings
  236. API struct {
  237. MaxResponseItems int
  238. }
  239. // UI settings
  240. UI struct {
  241. ExplorePagingNum int
  242. IssuePagingNum int
  243. FeedMaxCommitNum int
  244. ThemeColorMetaTag string
  245. MaxDisplayFileSize int64
  246. Admin struct {
  247. UserPagingNum int
  248. RepoPagingNum int
  249. NoticePagingNum int
  250. OrgPagingNum int
  251. } `ini:"ui.admin"`
  252. User struct {
  253. RepoPagingNum int
  254. NewsFeedPagingNum int
  255. CommitsPagingNum int
  256. } `ini:"ui.user"`
  257. }
  258. // I18n settings
  259. Langs []string
  260. Names []string
  261. dateLangs map[string]string
  262. // Highlight settings are loaded in modules/template/hightlight.go
  263. // Other settings
  264. ShowFooterBranding bool
  265. ShowFooterVersion bool
  266. ShowFooterTemplateLoadTime bool
  267. SupportMiniWinService bool
  268. // Global setting objects
  269. Cfg *ini.File
  270. CustomPath string // Custom directory path
  271. CustomConf string
  272. ProdMode bool
  273. RunUser string
  274. IsWindows bool
  275. HasRobotsTxt bool
  276. )
  277. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  278. func DateLang(lang string) string {
  279. name, ok := dateLangs[lang]
  280. if ok {
  281. return name
  282. }
  283. return "en"
  284. }
  285. // execPath returns the executable path.
  286. func execPath() (string, error) {
  287. file, err := exec.LookPath(os.Args[0])
  288. if err != nil {
  289. return "", err
  290. }
  291. return filepath.Abs(file)
  292. }
  293. func init() {
  294. IsWindows = runtime.GOOS == "windows"
  295. log.New(log.CONSOLE, log.ConsoleConfig{})
  296. var err error
  297. if AppPath, err = execPath(); err != nil {
  298. log.Fatal(2, "Fail to get app path: %v\n", err)
  299. }
  300. // Note: we don't use path.Dir here because it does not handle case
  301. // which path starts with two "/" in Windows: "//psf/Home/..."
  302. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  303. }
  304. // WorkDir returns absolute path of work directory.
  305. func WorkDir() (string, error) {
  306. wd := os.Getenv("GOGS_WORK_DIR")
  307. if len(wd) > 0 {
  308. return wd, nil
  309. }
  310. i := strings.LastIndex(AppPath, "/")
  311. if i == -1 {
  312. return AppPath, nil
  313. }
  314. return AppPath[:i], nil
  315. }
  316. func forcePathSeparator(path string) {
  317. if strings.Contains(path, "\\") {
  318. log.Fatal(2, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  319. }
  320. }
  321. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  322. // actual user that runs the app. The first return value is the actual user name.
  323. // This check is ignored under Windows since SSH remote login is not the main
  324. // method to login on Windows.
  325. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  326. if IsWindows {
  327. return "", true
  328. }
  329. currentUser := user.CurrentUsername()
  330. return currentUser, runUser == currentUser
  331. }
  332. // getOpenSSHVersion parses and returns string representation of OpenSSH version
  333. // returned by command "ssh -V".
  334. func getOpenSSHVersion() string {
  335. // Note: somehow version is printed to stderr
  336. _, stderr, err := process.Exec("getOpenSSHVersion", "ssh", "-V")
  337. if err != nil {
  338. log.Fatal(2, "Fail to get OpenSSH version: %v - %s", err, stderr)
  339. }
  340. // Trim unused information: https://github.com/gogs/gogs/issues/4507#issuecomment-305150441
  341. version := strings.TrimRight(strings.Fields(stderr)[0], ",1234567890")
  342. version = strings.TrimSuffix(strings.TrimPrefix(version, "OpenSSH_"), "p")
  343. return version
  344. }
  345. // NewContext initializes configuration context.
  346. // NOTE: do not print any log except error.
  347. func NewContext() {
  348. workDir, err := WorkDir()
  349. if err != nil {
  350. log.Fatal(2, "Fail to get work directory: %v", err)
  351. }
  352. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  353. if err != nil {
  354. log.Fatal(2, "Fail to parse 'conf/app.ini': %v", err)
  355. }
  356. CustomPath = os.Getenv("GOGS_CUSTOM")
  357. if len(CustomPath) == 0 {
  358. CustomPath = workDir + "/custom"
  359. }
  360. if len(CustomConf) == 0 {
  361. CustomConf = CustomPath + "/conf/app.ini"
  362. }
  363. if com.IsFile(CustomConf) {
  364. if err = Cfg.Append(CustomConf); err != nil {
  365. log.Fatal(2, "Fail to load custom conf '%s': %v", CustomConf, err)
  366. }
  367. } else {
  368. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  369. }
  370. Cfg.NameMapper = ini.AllCapsUnderscore
  371. homeDir, err := com.HomeDir()
  372. if err != nil {
  373. log.Fatal(2, "Fail to get home directory: %v", err)
  374. }
  375. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  376. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  377. forcePathSeparator(LogRootPath)
  378. sec := Cfg.Section("server")
  379. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs")
  380. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  381. if AppURL[len(AppURL)-1] != '/' {
  382. AppURL += "/"
  383. }
  384. // Check if has app suburl.
  385. url, err := url.Parse(AppURL)
  386. if err != nil {
  387. log.Fatal(2, "Invalid ROOT_URL '%s': %s", AppURL, err)
  388. }
  389. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  390. // This value is empty if site does not have sub-url.
  391. AppSubURL = strings.TrimSuffix(url.Path, "/")
  392. AppSubURLDepth = strings.Count(AppSubURL, "/")
  393. Protocol = SCHEME_HTTP
  394. if sec.Key("PROTOCOL").String() == "https" {
  395. Protocol = SCHEME_HTTPS
  396. CertFile = sec.Key("CERT_FILE").String()
  397. KeyFile = sec.Key("KEY_FILE").String()
  398. TLSMinVersion = sec.Key("TLS_MIN_VERSION").String()
  399. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  400. Protocol = SCHEME_FCGI
  401. } else if sec.Key("PROTOCOL").String() == "unix" {
  402. Protocol = SCHEME_UNIX_SOCKET
  403. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  404. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  405. if err != nil || UnixSocketPermissionParsed > 0777 {
  406. log.Fatal(2, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  407. }
  408. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  409. }
  410. Domain = sec.Key("DOMAIN").MustString("localhost")
  411. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  412. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  413. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  414. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  415. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  416. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  417. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  418. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  419. switch sec.Key("LANDING_PAGE").MustString("home") {
  420. case "explore":
  421. LandingPageURL = LANDING_PAGE_EXPLORE
  422. default:
  423. LandingPageURL = LANDING_PAGE_HOME
  424. }
  425. SSH.RootPath = path.Join(homeDir, ".ssh")
  426. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  427. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  428. SSH.KeyTestPath = os.TempDir()
  429. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  430. log.Fatal(2, "Fail to map SSH settings: %v", err)
  431. }
  432. if SSH.Disabled {
  433. SSH.StartBuiltinServer = false
  434. SSH.MinimumKeySizeCheck = false
  435. }
  436. if !SSH.Disabled && !SSH.StartBuiltinServer {
  437. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  438. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  439. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  440. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  441. }
  442. }
  443. if SSH.StartBuiltinServer {
  444. SSH.RewriteAuthorizedKeysAtStart = false
  445. }
  446. // Check if server is eligible for minimum key size check when user choose to enable.
  447. // Windows server and OpenSSH version lower than 5.1 (https://github.com/gogs/gogs/issues/4507)
  448. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  449. if SSH.MinimumKeySizeCheck &&
  450. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  451. SSH.MinimumKeySizeCheck = false
  452. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  453. 1. Windows server
  454. 2. OpenSSH version is lower than 5.1`)
  455. }
  456. if SSH.MinimumKeySizeCheck {
  457. SSH.MinimumKeySizes = map[string]int{}
  458. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  459. if key.MustInt() != -1 {
  460. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  461. }
  462. }
  463. }
  464. sec = Cfg.Section("security")
  465. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  466. SecretKey = sec.Key("SECRET_KEY").String()
  467. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  468. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  469. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  470. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  471. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  472. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  473. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  474. sec = Cfg.Section("attachment")
  475. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  476. if !filepath.IsAbs(AttachmentPath) {
  477. AttachmentPath = path.Join(workDir, AttachmentPath)
  478. }
  479. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  480. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  481. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  482. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  483. TimeFormat = map[string]string{
  484. "ANSIC": time.ANSIC,
  485. "UnixDate": time.UnixDate,
  486. "RubyDate": time.RubyDate,
  487. "RFC822": time.RFC822,
  488. "RFC822Z": time.RFC822Z,
  489. "RFC850": time.RFC850,
  490. "RFC1123": time.RFC1123,
  491. "RFC1123Z": time.RFC1123Z,
  492. "RFC3339": time.RFC3339,
  493. "RFC3339Nano": time.RFC3339Nano,
  494. "Kitchen": time.Kitchen,
  495. "Stamp": time.Stamp,
  496. "StampMilli": time.StampMilli,
  497. "StampMicro": time.StampMicro,
  498. "StampNano": time.StampNano,
  499. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  500. RunUser = Cfg.Section("").Key("RUN_USER").String()
  501. // Does not check run user when the install lock is off.
  502. if InstallLock {
  503. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  504. if !match {
  505. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  506. }
  507. }
  508. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  509. // Determine and create root git repository path.
  510. sec = Cfg.Section("repository")
  511. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  512. forcePathSeparator(RepoRootPath)
  513. if !filepath.IsAbs(RepoRootPath) {
  514. RepoRootPath = path.Join(workDir, RepoRootPath)
  515. } else {
  516. RepoRootPath = path.Clean(RepoRootPath)
  517. }
  518. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  519. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  520. log.Fatal(2, "Fail to map Repository settings: %v", err)
  521. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  522. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  523. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  524. log.Fatal(2, "Fail to map Repository.Upload settings: %v", err)
  525. }
  526. if !filepath.IsAbs(Repository.Upload.TempPath) {
  527. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  528. }
  529. sec = Cfg.Section("picture")
  530. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  531. forcePathSeparator(AvatarUploadPath)
  532. if !filepath.IsAbs(AvatarUploadPath) {
  533. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  534. }
  535. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  536. case "duoshuo":
  537. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  538. case "gravatar":
  539. GravatarSource = "https://secure.gravatar.com/avatar/"
  540. case "libravatar":
  541. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  542. default:
  543. GravatarSource = source
  544. }
  545. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  546. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  547. if OfflineMode {
  548. DisableGravatar = true
  549. EnableFederatedAvatar = false
  550. }
  551. if DisableGravatar {
  552. EnableFederatedAvatar = false
  553. }
  554. if EnableFederatedAvatar {
  555. LibravatarService = libravatar.New()
  556. parts := strings.Split(GravatarSource, "/")
  557. if len(parts) >= 3 {
  558. if parts[0] == "https:" {
  559. LibravatarService.SetUseHTTPS(true)
  560. LibravatarService.SetSecureFallbackHost(parts[2])
  561. } else {
  562. LibravatarService.SetUseHTTPS(false)
  563. LibravatarService.SetFallbackHost(parts[2])
  564. }
  565. }
  566. }
  567. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  568. log.Fatal(2, "Fail to map HTTP settings: %v", err)
  569. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  570. log.Fatal(2, "Fail to map Webhook settings: %v", err)
  571. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  572. log.Fatal(2, "Fail to map Release.Attachment settings: %v", err)
  573. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  574. log.Fatal(2, "Fail to map Markdown settings: %v", err)
  575. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  576. log.Fatal(2, "Fail to map Smartypants settings: %v", err)
  577. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  578. log.Fatal(2, "Fail to map Admin settings: %v", err)
  579. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  580. log.Fatal(2, "Fail to map Cron settings: %v", err)
  581. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  582. log.Fatal(2, "Fail to map Git settings: %v", err)
  583. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  584. log.Fatal(2, "Fail to map Mirror settings: %v", err)
  585. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  586. log.Fatal(2, "Fail to map API settings: %v", err)
  587. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  588. log.Fatal(2, "Fail to map UI settings: %v", err)
  589. }
  590. if Mirror.DefaultInterval <= 0 {
  591. Mirror.DefaultInterval = 24
  592. }
  593. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  594. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  595. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  596. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  597. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  598. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  599. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  600. }
  601. var Service struct {
  602. ActiveCodeLives int
  603. ResetPwdCodeLives int
  604. RegisterEmailConfirm bool
  605. DisableRegistration bool
  606. ShowRegistrationButton bool
  607. RequireSignInView bool
  608. EnableNotifyMail bool
  609. EnableReverseProxyAuth bool
  610. EnableReverseProxyAutoRegister bool
  611. EnableCaptcha bool
  612. }
  613. func newService() {
  614. sec := Cfg.Section("service")
  615. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  616. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  617. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  618. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  619. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  620. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  621. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  622. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  623. }
  624. func newLogService() {
  625. if len(BuildTime) > 0 {
  626. log.Trace("Build Time: %s", BuildTime)
  627. log.Trace("Build Git Hash: %s", BuildGitHash)
  628. }
  629. // Because we always create a console logger as primary logger before all settings are loaded,
  630. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  631. hasConsole := false
  632. // Get and check log modes.
  633. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  634. LogConfigs = make([]interface{}, len(LogModes))
  635. levelNames := map[string]log.LEVEL{
  636. "trace": log.TRACE,
  637. "info": log.INFO,
  638. "warn": log.WARN,
  639. "error": log.ERROR,
  640. "fatal": log.FATAL,
  641. }
  642. for i, mode := range LogModes {
  643. mode = strings.ToLower(strings.TrimSpace(mode))
  644. sec, err := Cfg.GetSection("log." + mode)
  645. if err != nil {
  646. log.Fatal(2, "Unknown logger mode: %s", mode)
  647. }
  648. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  649. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  650. v = strings.ToLower(v)
  651. if com.IsSliceContainsStr(validLevels, v) {
  652. return v
  653. }
  654. return "trace"
  655. })
  656. level := levelNames[name]
  657. // Generate log configuration.
  658. switch log.MODE(mode) {
  659. case log.CONSOLE:
  660. hasConsole = true
  661. LogConfigs[i] = log.ConsoleConfig{
  662. Level: level,
  663. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  664. }
  665. case log.FILE:
  666. logPath := path.Join(LogRootPath, "gogs.log")
  667. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  668. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  669. }
  670. LogConfigs[i] = log.FileConfig{
  671. Level: level,
  672. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  673. Filename: logPath,
  674. FileRotationConfig: log.FileRotationConfig{
  675. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  676. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  677. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  678. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  679. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  680. },
  681. }
  682. case log.SLACK:
  683. LogConfigs[i] = log.SlackConfig{
  684. Level: level,
  685. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  686. URL: sec.Key("URL").String(),
  687. }
  688. case log.DISCORD:
  689. LogConfigs[i] = log.DiscordConfig{
  690. Level: level,
  691. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  692. URL: sec.Key("URL").String(),
  693. Username: sec.Key("USERNAME").String(),
  694. }
  695. }
  696. log.New(log.MODE(mode), LogConfigs[i])
  697. log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(name))
  698. }
  699. // Make sure everyone gets version info printed.
  700. log.Info("%s %s", AppName, AppVer)
  701. if !hasConsole {
  702. log.Delete(log.CONSOLE)
  703. }
  704. }
  705. func newCacheService() {
  706. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  707. switch CacheAdapter {
  708. case "memory":
  709. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  710. case "redis", "memcache":
  711. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  712. default:
  713. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  714. }
  715. log.Info("Cache Service Enabled")
  716. }
  717. func newSessionService() {
  718. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  719. []string{"memory", "file", "redis", "mysql"})
  720. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  721. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  722. SessionConfig.CookiePath = AppSubURL
  723. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  724. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  725. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  726. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  727. log.Info("Session Service Enabled")
  728. }
  729. // Mailer represents mail service.
  730. type Mailer struct {
  731. QueueLength int
  732. SubjectPrefix string
  733. Host string
  734. From string
  735. FromEmail string
  736. User, Passwd string
  737. DisableHelo bool
  738. HeloHostname string
  739. SkipVerify bool
  740. UseCertificate bool
  741. CertFile, KeyFile string
  742. UsePlainText bool
  743. }
  744. var (
  745. MailService *Mailer
  746. )
  747. // newMailService initializes mail service options from configuration.
  748. // No non-error log will be printed in hook mode.
  749. func newMailService() {
  750. sec := Cfg.Section("mailer")
  751. if !sec.Key("ENABLED").MustBool() {
  752. return
  753. }
  754. MailService = &Mailer{
  755. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  756. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  757. Host: sec.Key("HOST").String(),
  758. User: sec.Key("USER").String(),
  759. Passwd: sec.Key("PASSWD").String(),
  760. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  761. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  762. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  763. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  764. CertFile: sec.Key("CERT_FILE").String(),
  765. KeyFile: sec.Key("KEY_FILE").String(),
  766. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  767. }
  768. MailService.From = sec.Key("FROM").MustString(MailService.User)
  769. if len(MailService.From) > 0 {
  770. parsed, err := mail.ParseAddress(MailService.From)
  771. if err != nil {
  772. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  773. }
  774. MailService.FromEmail = parsed.Address
  775. }
  776. if HookMode {
  777. return
  778. }
  779. log.Info("Mail Service Enabled")
  780. }
  781. func newRegisterMailService() {
  782. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  783. return
  784. } else if MailService == nil {
  785. log.Warn("Register Mail Service: Mail Service is not enabled")
  786. return
  787. }
  788. Service.RegisterEmailConfirm = true
  789. log.Info("Register Mail Service Enabled")
  790. }
  791. // newNotifyMailService initializes notification email service options from configuration.
  792. // No non-error log will be printed in hook mode.
  793. func newNotifyMailService() {
  794. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  795. return
  796. } else if MailService == nil {
  797. log.Warn("Notify Mail Service: Mail Service is not enabled")
  798. return
  799. }
  800. Service.EnableNotifyMail = true
  801. if HookMode {
  802. return
  803. }
  804. log.Info("Notify Mail Service Enabled")
  805. }
  806. func NewService() {
  807. newService()
  808. }
  809. func NewServices() {
  810. newService()
  811. newLogService()
  812. newCacheService()
  813. newSessionService()
  814. newMailService()
  815. newRegisterMailService()
  816. newNotifyMailService()
  817. }
  818. // HookMode indicates whether program starts as Git server-side hook callback.
  819. var HookMode bool
  820. // NewPostReceiveHookServices initializes all services that are needed by
  821. // Git server-side post-receive hook callback.
  822. func NewPostReceiveHookServices() {
  823. HookMode = true
  824. newService()
  825. newMailService()
  826. newNotifyMailService()
  827. }