setting.go 30 KB

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