setting.go 30 KB

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