setting.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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 settingsS
  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. // Repository editor settings
  119. Editor struct {
  120. LineWrapExtensions []string
  121. PreviewableFileModes []string
  122. } `ini:"-"`
  123. // Repository upload settings
  124. Upload struct {
  125. Enabled bool
  126. TempPath string
  127. AllowedTypes []string `delim:"|"`
  128. FileMaxSize int64
  129. AnexFileMinSize int64
  130. MaxFiles int
  131. } `ini:"-"`
  132. }
  133. RepoRootPath string
  134. ScriptType string
  135. // Webhook settings
  136. Webhook struct {
  137. Types []string
  138. QueueLength int
  139. DeliverTimeout int
  140. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  141. PagingNum int
  142. }
  143. // Release settigns
  144. Release struct {
  145. Attachment struct {
  146. Enabled bool
  147. TempPath string
  148. AllowedTypes []string `delim:"|"`
  149. MaxSize int64
  150. MaxFiles int
  151. } `ini:"-"`
  152. }
  153. // Markdown sttings
  154. Markdown struct {
  155. EnableHardLineBreak bool
  156. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  157. FileExtensions []string
  158. }
  159. // Smartypants settings
  160. Smartypants struct {
  161. Enabled bool
  162. Fractions bool
  163. Dashes bool
  164. LatexDashes bool
  165. AngledQuotes bool
  166. }
  167. // Admin settings
  168. Admin struct {
  169. DisableRegularOrgCreation bool
  170. }
  171. // Picture settings
  172. AvatarUploadPath string
  173. RepositoryAvatarUploadPath string
  174. GravatarSource string
  175. DisableGravatar bool
  176. EnableFederatedAvatar bool
  177. LibravatarService *libravatar.Libravatar
  178. // Log settings
  179. LogRootPath string
  180. LogModes []string
  181. LogConfigs []interface{}
  182. // Attachment settings
  183. AttachmentPath string
  184. AttachmentAllowedTypes string
  185. AttachmentMaxSize int64
  186. AttachmentMaxFiles int
  187. AttachmentEnabled bool
  188. // Time settings
  189. TimeFormat string
  190. // Cache settings
  191. CacheAdapter string
  192. CacheInterval int
  193. CacheConn string
  194. // Session settings
  195. SessionConfig session.Options
  196. CSRFCookieName string
  197. // Cron tasks
  198. Cron struct {
  199. UpdateMirror struct {
  200. Enabled bool
  201. RunAtStart bool
  202. Schedule string
  203. } `ini:"cron.update_mirrors"`
  204. RepoHealthCheck struct {
  205. Enabled bool
  206. RunAtStart bool
  207. Schedule string
  208. Timeout time.Duration
  209. Args []string `delim:" "`
  210. } `ini:"cron.repo_health_check"`
  211. CheckRepoStats struct {
  212. Enabled bool
  213. RunAtStart bool
  214. Schedule string
  215. } `ini:"cron.check_repo_stats"`
  216. RepoArchiveCleanup struct {
  217. Enabled bool
  218. RunAtStart bool
  219. Schedule string
  220. OlderThan time.Duration
  221. } `ini:"cron.repo_archive_cleanup"`
  222. }
  223. // Git settings
  224. Git struct {
  225. Version string `ini:"-"`
  226. DisableDiffHighlight bool
  227. MaxGitDiffLines int
  228. MaxGitDiffLineCharacters int
  229. MaxGitDiffFiles int
  230. GCArgs []string `ini:"GC_ARGS" delim:" "`
  231. Timeout struct {
  232. Migrate int
  233. Mirror int
  234. Clone int
  235. Pull int
  236. GC int `ini:"GC"`
  237. } `ini:"git.timeout"`
  238. }
  239. // Mirror settings
  240. Mirror struct {
  241. DefaultInterval int
  242. }
  243. // API settings
  244. API struct {
  245. MaxResponseItems int
  246. }
  247. // UI settings
  248. UI struct {
  249. ExplorePagingNum int
  250. IssuePagingNum int
  251. FeedMaxCommitNum int
  252. ThemeColorMetaTag string
  253. MaxDisplayFileSize int64
  254. MaxLineHighlight int
  255. Admin struct {
  256. UserPagingNum int
  257. RepoPagingNum int
  258. NoticePagingNum int
  259. OrgPagingNum int
  260. } `ini:"ui.admin"`
  261. User struct {
  262. RepoPagingNum int
  263. NewsFeedPagingNum int
  264. CommitsPagingNum int
  265. } `ini:"ui.user"`
  266. }
  267. // Prometheus settings
  268. Prometheus struct {
  269. Enabled bool
  270. EnableBasicAuth bool
  271. BasicAuthUsername string
  272. BasicAuthPassword string
  273. }
  274. // I18n settings
  275. Langs []string
  276. Names []string
  277. dateLangs map[string]string
  278. // Highlight settings are loaded in modules/template/hightlight.go
  279. // Other settings
  280. ShowFooterBranding bool
  281. ShowFooterVersion bool
  282. ShowFooterTemplateLoadTime bool
  283. SupportMiniWinService bool
  284. // Global setting objects
  285. Cfg *ini.File
  286. CustomPath string // Custom directory path
  287. CustomConf string
  288. ProdMode bool
  289. RunUser string
  290. IsWindows bool
  291. HasRobotsTxt bool
  292. Search struct {
  293. Do bool
  294. IndexUrl string
  295. SearchUrl string
  296. }
  297. Doi struct {
  298. Do bool
  299. DoiUrl string
  300. DoiKey string
  301. DoiBase string
  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://github.com/gogs/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. }, bindata.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. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  455. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  456. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  457. switch sec.Key("LANDING_PAGE").MustString("home") {
  458. case "explore":
  459. LandingPageURL = LANDING_PAGE_EXPLORE
  460. default:
  461. LandingPageURL = LANDING_PAGE_HOME
  462. }
  463. SSH.RootPath = path.Join(homeDir, ".ssh")
  464. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  465. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  466. SSH.KeyTestPath = os.TempDir()
  467. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  468. log.Fatal(2, "Fail to map SSH settings: %v", err)
  469. }
  470. if SSH.Disabled {
  471. SSH.StartBuiltinServer = false
  472. SSH.MinimumKeySizeCheck = false
  473. }
  474. if !SSH.Disabled && !SSH.StartBuiltinServer {
  475. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  476. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  477. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  478. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  479. }
  480. }
  481. if SSH.StartBuiltinServer {
  482. SSH.RewriteAuthorizedKeysAtStart = false
  483. }
  484. // Check if server is eligible for minimum key size check when user choose to enable.
  485. // Windows server and OpenSSH version lower than 5.1 (https://github.com/gogs/gogs/issues/4507)
  486. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  487. if SSH.MinimumKeySizeCheck &&
  488. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  489. SSH.MinimumKeySizeCheck = false
  490. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  491. 1. Windows server
  492. 2. OpenSSH version is lower than 5.1`)
  493. }
  494. if SSH.MinimumKeySizeCheck {
  495. SSH.MinimumKeySizes = map[string]int{}
  496. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  497. if key.MustInt() != -1 {
  498. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  499. }
  500. }
  501. }
  502. sec = Cfg.Section("security")
  503. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  504. SecretKey = sec.Key("SECRET_KEY").String()
  505. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  506. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  507. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  508. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  509. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  510. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  511. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  512. sec = Cfg.Section("attachment")
  513. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  514. if !filepath.IsAbs(AttachmentPath) {
  515. AttachmentPath = path.Join(workDir, AttachmentPath)
  516. }
  517. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  518. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  519. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  520. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  521. TimeFormat = map[string]string{
  522. "ANSIC": time.ANSIC,
  523. "UnixDate": time.UnixDate,
  524. "RubyDate": time.RubyDate,
  525. "RFC822": time.RFC822,
  526. "RFC822Z": time.RFC822Z,
  527. "RFC850": time.RFC850,
  528. "RFC1123": time.RFC1123,
  529. "RFC1123Z": time.RFC1123Z,
  530. "RFC3339": time.RFC3339,
  531. "RFC3339Nano": time.RFC3339Nano,
  532. "Kitchen": time.Kitchen,
  533. "Stamp": time.Stamp,
  534. "StampMilli": time.StampMilli,
  535. "StampMicro": time.StampMicro,
  536. "StampNano": time.StampNano,
  537. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  538. RunUser = Cfg.Section("").Key("RUN_USER").String()
  539. // Does not check run user when the install lock is off.
  540. if InstallLock {
  541. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  542. if !match {
  543. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  544. }
  545. }
  546. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  547. // Determine and create root git repository path.
  548. sec = Cfg.Section("repository")
  549. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  550. forcePathSeparator(RepoRootPath)
  551. if !filepath.IsAbs(RepoRootPath) {
  552. RepoRootPath = path.Join(workDir, RepoRootPath)
  553. } else {
  554. RepoRootPath = path.Clean(RepoRootPath)
  555. }
  556. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  557. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  558. log.Fatal(2, "Fail to map Repository settings: %v", err)
  559. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  560. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  561. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  562. log.Fatal(2, "Fail to map Repository.Upload settings: %v", err)
  563. }
  564. if !filepath.IsAbs(Repository.Upload.TempPath) {
  565. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  566. }
  567. sec = Cfg.Section("picture")
  568. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  569. forcePathSeparator(AvatarUploadPath)
  570. if !filepath.IsAbs(AvatarUploadPath) {
  571. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  572. }
  573. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "repo-avatars"))
  574. forcePathSeparator(RepositoryAvatarUploadPath)
  575. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  576. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  577. }
  578. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  579. case "duoshuo":
  580. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  581. case "gravatar":
  582. GravatarSource = "https://secure.gravatar.com/avatar/"
  583. case "libravatar":
  584. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  585. default:
  586. GravatarSource = source
  587. }
  588. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  589. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  590. if OfflineMode {
  591. DisableGravatar = true
  592. EnableFederatedAvatar = false
  593. }
  594. if DisableGravatar {
  595. EnableFederatedAvatar = false
  596. }
  597. if EnableFederatedAvatar {
  598. LibravatarService = libravatar.New()
  599. parts := strings.Split(GravatarSource, "/")
  600. if len(parts) >= 3 {
  601. if parts[0] == "https:" {
  602. LibravatarService.SetUseHTTPS(true)
  603. LibravatarService.SetSecureFallbackHost(parts[2])
  604. } else {
  605. LibravatarService.SetUseHTTPS(false)
  606. LibravatarService.SetFallbackHost(parts[2])
  607. }
  608. }
  609. }
  610. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  611. log.Fatal(2, "Failed to map HTTP settings: %v", err)
  612. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  613. log.Fatal(2, "Failed to map Webhook settings: %v", err)
  614. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  615. log.Fatal(2, "Failed to map Release.Attachment settings: %v", err)
  616. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  617. log.Fatal(2, "Failed to map Markdown settings: %v", err)
  618. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  619. log.Fatal(2, "Failed to map Smartypants settings: %v", err)
  620. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  621. log.Fatal(2, "Failed to map Admin settings: %v", err)
  622. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  623. log.Fatal(2, "Failed to map Cron settings: %v", err)
  624. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  625. log.Fatal(2, "Failed to map Git settings: %v", err)
  626. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  627. log.Fatal(2, "Failed to map Mirror settings: %v", err)
  628. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  629. log.Fatal(2, "Failed to map API settings: %v", err)
  630. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  631. log.Fatal(2, "Failed to map UI settings: %v", err)
  632. } else if err = Cfg.Section("prometheus").MapTo(&Prometheus); err != nil {
  633. log.Fatal(2, "Failed to map Prometheus settings: %v", err)
  634. } else if err = Cfg.Section("search").MapTo(&Search); err != nil {
  635. log.Fatal(2, "Fail to map Search settings: %v", err)
  636. } else if err = Cfg.Section("doi").MapTo(&Doi); err != nil {
  637. log.Fatal(2, "Fail to map Doi settings: %v", err)
  638. } else if err = Cfg.Section("cliconfig").MapTo(&CliConfig); err != nil {
  639. log.Fatal(2, "Fail to map Client config settings: %v", err)
  640. } else if err = Cfg.Section("dav").MapTo(&WebDav); err != nil {
  641. log.Fatal(2, "Fail to map WebDav settings: %v", err)
  642. }
  643. if Mirror.DefaultInterval <= 0 {
  644. Mirror.DefaultInterval = 24
  645. }
  646. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  647. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  648. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  649. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  650. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  651. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  652. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  653. }
  654. var Service struct {
  655. ActiveCodeLives int
  656. ResetPwdCodeLives int
  657. RegisterEmailConfirm bool
  658. DisableRegistration bool
  659. ShowRegistrationButton bool
  660. RequireSignInView bool
  661. EnableNotifyMail bool
  662. EnableReverseProxyAuth bool
  663. EnableReverseProxyAutoRegister bool
  664. EnableCaptcha bool
  665. }
  666. func newService() {
  667. sec := Cfg.Section("service")
  668. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  669. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  670. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  671. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  672. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  673. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  674. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  675. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  676. }
  677. func newLogService() {
  678. if len(BuildTime) > 0 {
  679. log.Trace("Build Time: %s", BuildTime)
  680. log.Trace("Build Git Hash: %s", BuildGitHash)
  681. }
  682. // Because we always create a console logger as primary logger before all settings are loaded,
  683. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  684. hasConsole := false
  685. // Get and check log modes.
  686. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  687. LogConfigs = make([]interface{}, len(LogModes))
  688. levelNames := map[string]log.LEVEL{
  689. "trace": log.TRACE,
  690. "info": log.INFO,
  691. "warn": log.WARN,
  692. "error": log.ERROR,
  693. "fatal": log.FATAL,
  694. }
  695. for i, mode := range LogModes {
  696. mode = strings.ToLower(strings.TrimSpace(mode))
  697. sec, err := Cfg.GetSection("log." + mode)
  698. if err != nil {
  699. log.Fatal(2, "Unknown logger mode: %s", mode)
  700. }
  701. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  702. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  703. v = strings.ToLower(v)
  704. if com.IsSliceContainsStr(validLevels, v) {
  705. return v
  706. }
  707. return "trace"
  708. })
  709. level := levelNames[name]
  710. // Generate log configuration.
  711. switch log.MODE(mode) {
  712. case log.CONSOLE:
  713. hasConsole = true
  714. LogConfigs[i] = log.ConsoleConfig{
  715. Level: level,
  716. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  717. }
  718. case log.FILE:
  719. logPath := path.Join(LogRootPath, "gogs.log")
  720. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  721. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  722. }
  723. LogConfigs[i] = log.FileConfig{
  724. Level: level,
  725. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  726. Filename: logPath,
  727. FileRotationConfig: log.FileRotationConfig{
  728. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  729. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  730. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  731. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  732. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  733. },
  734. }
  735. case log.SLACK:
  736. LogConfigs[i] = log.SlackConfig{
  737. Level: level,
  738. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  739. URL: sec.Key("URL").String(),
  740. }
  741. case log.DISCORD:
  742. LogConfigs[i] = log.DiscordConfig{
  743. Level: level,
  744. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  745. URL: sec.Key("URL").String(),
  746. Username: sec.Key("USERNAME").String(),
  747. }
  748. }
  749. log.New(log.MODE(mode), LogConfigs[i])
  750. log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(name))
  751. }
  752. // Make sure everyone gets version info printed.
  753. log.Info("%s %s", AppName, AppVer)
  754. if !hasConsole {
  755. log.Delete(log.CONSOLE)
  756. }
  757. }
  758. func newCacheService() {
  759. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  760. switch CacheAdapter {
  761. case "memory":
  762. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  763. case "redis", "memcache":
  764. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  765. default:
  766. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  767. }
  768. log.Info("Cache Service Enabled")
  769. }
  770. func newSessionService() {
  771. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  772. []string{"memory", "file", "redis", "mysql"})
  773. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  774. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  775. SessionConfig.CookiePath = AppSubURL
  776. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  777. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  778. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  779. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  780. log.Info("Session Service Enabled")
  781. }
  782. // Mailer represents mail service.
  783. type Mailer struct {
  784. QueueLength int
  785. SubjectPrefix string
  786. Host string
  787. From string
  788. FromEmail string
  789. User, Passwd string
  790. DisableHelo bool
  791. HeloHostname string
  792. SkipVerify bool
  793. UseCertificate bool
  794. CertFile, KeyFile string
  795. UsePlainText bool
  796. AddPlainTextAlt bool
  797. }
  798. var (
  799. MailService *Mailer
  800. )
  801. // newMailService initializes mail service options from configuration.
  802. // No non-error log will be printed in hook mode.
  803. func newMailService() {
  804. sec := Cfg.Section("mailer")
  805. if !sec.Key("ENABLED").MustBool() {
  806. return
  807. }
  808. MailService = &Mailer{
  809. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  810. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  811. Host: sec.Key("HOST").String(),
  812. User: sec.Key("USER").String(),
  813. Passwd: sec.Key("PASSWD").String(),
  814. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  815. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  816. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  817. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  818. CertFile: sec.Key("CERT_FILE").String(),
  819. KeyFile: sec.Key("KEY_FILE").String(),
  820. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  821. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  822. }
  823. MailService.From = sec.Key("FROM").MustString(MailService.User)
  824. if len(MailService.From) > 0 {
  825. parsed, err := mail.ParseAddress(MailService.From)
  826. if err != nil {
  827. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  828. }
  829. MailService.FromEmail = parsed.Address
  830. }
  831. if HookMode {
  832. return
  833. }
  834. log.Info("Mail Service Enabled")
  835. }
  836. func newRegisterMailService() {
  837. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  838. return
  839. } else if MailService == nil {
  840. log.Warn("Register Mail Service: Mail Service is not enabled")
  841. return
  842. }
  843. Service.RegisterEmailConfirm = true
  844. log.Info("Register Mail Service Enabled")
  845. }
  846. // newNotifyMailService initializes notification email service options from configuration.
  847. // No non-error log will be printed in hook mode.
  848. func newNotifyMailService() {
  849. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  850. return
  851. } else if MailService == nil {
  852. log.Warn("Notify Mail Service: Mail Service is not enabled")
  853. return
  854. }
  855. Service.EnableNotifyMail = true
  856. if HookMode {
  857. return
  858. }
  859. log.Info("Notify Mail Service Enabled")
  860. }
  861. func NewService() {
  862. newService()
  863. }
  864. func NewServices() {
  865. newService()
  866. newLogService()
  867. newCacheService()
  868. newSessionService()
  869. newMailService()
  870. newRegisterMailService()
  871. newNotifyMailService()
  872. }
  873. // HookMode indicates whether program starts as Git server-side hook callback.
  874. var HookMode bool
  875. // NewPostReceiveHookServices initializes all services that are needed by
  876. // Git server-side post-receive hook callback.
  877. func NewPostReceiveHookServices() {
  878. HookMode = true
  879. newService()
  880. newMailService()
  881. newNotifyMailService()
  882. }