setting.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. EnableLocalPathMigration bool
  112. CommitsFetchConcurrency int
  113. EnableRawFileRenderMode bool
  114. RawCaptchaMinFileSize int64
  115. CaptchaMinFileSize int64
  116. // Repository editor settings
  117. Editor struct {
  118. LineWrapExtensions []string
  119. PreviewableFileModes []string
  120. } `ini:"-"`
  121. // Repository upload settings
  122. Upload struct {
  123. Enabled bool
  124. TempPath string
  125. AllowedTypes []string `delim:"|"`
  126. FileMaxSize int64
  127. AnexFileMinSize int64
  128. MaxFiles int
  129. } `ini:"-"`
  130. }
  131. RepoRootPath string
  132. ScriptType string
  133. // Webhook settings
  134. Webhook struct {
  135. Types []string
  136. QueueLength int
  137. DeliverTimeout int
  138. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  139. PagingNum int
  140. }
  141. // Release settigns
  142. Release struct {
  143. Attachment struct {
  144. Enabled bool
  145. TempPath string
  146. AllowedTypes []string `delim:"|"`
  147. MaxSize int64
  148. MaxFiles int
  149. } `ini:"-"`
  150. }
  151. // Markdown sttings
  152. Markdown struct {
  153. EnableHardLineBreak bool
  154. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  155. FileExtensions []string
  156. }
  157. // Smartypants settings
  158. Smartypants struct {
  159. Enabled bool
  160. Fractions bool
  161. Dashes bool
  162. LatexDashes bool
  163. AngledQuotes bool
  164. }
  165. // Admin settings
  166. Admin struct {
  167. DisableRegularOrgCreation bool
  168. }
  169. // Picture settings
  170. AvatarUploadPath string
  171. RepositoryAvatarUploadPath string
  172. GravatarSource string
  173. DisableGravatar bool
  174. EnableFederatedAvatar bool
  175. LibravatarService *libravatar.Libravatar
  176. // Log settings
  177. LogRootPath string
  178. LogModes []string
  179. LogConfigs []interface{}
  180. // Attachment settings
  181. AttachmentPath string
  182. AttachmentAllowedTypes string
  183. AttachmentMaxSize int64
  184. AttachmentMaxFiles int
  185. AttachmentEnabled bool
  186. // Time settings
  187. TimeFormat string
  188. // Cache settings
  189. CacheAdapter string
  190. CacheInterval int
  191. CacheConn string
  192. // Session settings
  193. SessionConfig session.Options
  194. CSRFCookieName string
  195. // Cron tasks
  196. Cron struct {
  197. UpdateMirror struct {
  198. Enabled bool
  199. RunAtStart bool
  200. Schedule string
  201. } `ini:"cron.update_mirrors"`
  202. RepoHealthCheck struct {
  203. Enabled bool
  204. RunAtStart bool
  205. Schedule string
  206. Timeout time.Duration
  207. Args []string `delim:" "`
  208. } `ini:"cron.repo_health_check"`
  209. CheckRepoStats struct {
  210. Enabled bool
  211. RunAtStart bool
  212. Schedule string
  213. } `ini:"cron.check_repo_stats"`
  214. RepoArchiveCleanup struct {
  215. Enabled bool
  216. RunAtStart bool
  217. Schedule string
  218. OlderThan time.Duration
  219. } `ini:"cron.repo_archive_cleanup"`
  220. }
  221. // Git settings
  222. Git struct {
  223. Version string `ini:"-"`
  224. DisableDiffHighlight bool
  225. MaxGitDiffLines int
  226. MaxGitDiffLineCharacters int
  227. MaxGitDiffFiles int
  228. GCArgs []string `ini:"GC_ARGS" delim:" "`
  229. Timeout struct {
  230. Migrate int
  231. Mirror int
  232. Clone int
  233. Pull int
  234. GC int `ini:"GC"`
  235. } `ini:"git.timeout"`
  236. }
  237. // Mirror settings
  238. Mirror struct {
  239. DefaultInterval int
  240. }
  241. // API settings
  242. API struct {
  243. MaxResponseItems int
  244. }
  245. // UI settings
  246. UI struct {
  247. ExplorePagingNum int
  248. IssuePagingNum int
  249. FeedMaxCommitNum int
  250. ThemeColorMetaTag string
  251. MaxDisplayFileSize int64
  252. MaxLineHighlight int
  253. Admin struct {
  254. UserPagingNum int
  255. RepoPagingNum int
  256. NoticePagingNum int
  257. OrgPagingNum int
  258. } `ini:"ui.admin"`
  259. User struct {
  260. RepoPagingNum int
  261. NewsFeedPagingNum int
  262. CommitsPagingNum int
  263. } `ini:"ui.user"`
  264. }
  265. // Prometheus settings
  266. Prometheus struct {
  267. Enabled bool
  268. EnableBasicAuth bool
  269. BasicAuthUsername string
  270. BasicAuthPassword string
  271. }
  272. // I18n settings
  273. Langs []string
  274. Names []string
  275. dateLangs map[string]string
  276. // Highlight settings are loaded in modules/template/hightlight.go
  277. // Other settings
  278. ShowFooterBranding bool
  279. ShowFooterVersion bool
  280. ShowFooterTemplateLoadTime bool
  281. SupportMiniWinService bool
  282. // Global setting objects
  283. Cfg *ini.File
  284. CustomPath string // Custom directory path
  285. CustomConf string
  286. ProdMode bool
  287. RunUser string
  288. IsWindows bool
  289. HasRobotsTxt bool
  290. Search struct {
  291. Do bool
  292. IndexUrl string
  293. SearchUrl string
  294. }
  295. Doi struct {
  296. Do bool
  297. DoiUrl string
  298. DoiKey string
  299. DoiBase string
  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, "Fail 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, "Fail to map Repository settings: %v", err)
  557. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  558. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  559. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  560. log.Fatal(2, "Fail 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, "Fail to map UI settings: %v", err)
  630. } else if err = Cfg.Section("search").MapTo(&Search); err != nil {
  631. log.Fatal(2, "Fail to map Search settings: %v", err)
  632. } else if err = Cfg.Section("doi").MapTo(&Doi); err != nil {
  633. log.Fatal(2, "Fail to map Doi settings: %v", err)
  634. } else if err = Cfg.Section("cliconfig").MapTo(&CliConfig); err != nil {
  635. log.Fatal(2, "Fail to map Client config settings: %v", err)
  636. } else if err = Cfg.Section("dav").MapTo(&WebDav); err != nil {
  637. log.Fatal(2, "Fail to map WebDav settings: %v", err)
  638. }
  639. if Mirror.DefaultInterval <= 0 {
  640. Mirror.DefaultInterval = 24
  641. }
  642. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  643. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  644. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  645. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  646. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  647. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  648. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  649. }
  650. var Service struct {
  651. ActiveCodeLives int
  652. ResetPwdCodeLives int
  653. RegisterEmailConfirm bool
  654. DisableRegistration bool
  655. ShowRegistrationButton bool
  656. RequireSignInView bool
  657. EnableNotifyMail bool
  658. EnableReverseProxyAuth bool
  659. EnableReverseProxyAutoRegister bool
  660. EnableCaptcha bool
  661. }
  662. func newService() {
  663. sec := Cfg.Section("service")
  664. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  665. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  666. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  667. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  668. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  669. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  670. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  671. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  672. }
  673. func newLogService() {
  674. if len(BuildTime) > 0 {
  675. log.Trace("Build Time: %s", BuildTime)
  676. log.Trace("Build Git Hash: %s", BuildGitHash)
  677. }
  678. // Because we always create a console logger as primary logger before all settings are loaded,
  679. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  680. hasConsole := false
  681. // Get and check log modes.
  682. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  683. LogConfigs = make([]interface{}, len(LogModes))
  684. levelNames := map[string]log.LEVEL{
  685. "trace": log.TRACE,
  686. "info": log.INFO,
  687. "warn": log.WARN,
  688. "error": log.ERROR,
  689. "fatal": log.FATAL,
  690. }
  691. for i, mode := range LogModes {
  692. mode = strings.ToLower(strings.TrimSpace(mode))
  693. sec, err := Cfg.GetSection("log." + mode)
  694. if err != nil {
  695. log.Fatal(2, "Unknown logger mode: %s", mode)
  696. }
  697. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  698. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  699. v = strings.ToLower(v)
  700. if com.IsSliceContainsStr(validLevels, v) {
  701. return v
  702. }
  703. return "trace"
  704. })
  705. level := levelNames[name]
  706. // Generate log configuration.
  707. switch log.MODE(mode) {
  708. case log.CONSOLE:
  709. hasConsole = true
  710. LogConfigs[i] = log.ConsoleConfig{
  711. Level: level,
  712. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  713. }
  714. case log.FILE:
  715. logPath := path.Join(LogRootPath, "gogs.log")
  716. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  717. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  718. }
  719. LogConfigs[i] = log.FileConfig{
  720. Level: level,
  721. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  722. Filename: logPath,
  723. FileRotationConfig: log.FileRotationConfig{
  724. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  725. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  726. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  727. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  728. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  729. },
  730. }
  731. case log.SLACK:
  732. LogConfigs[i] = log.SlackConfig{
  733. Level: level,
  734. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  735. URL: sec.Key("URL").String(),
  736. }
  737. case log.DISCORD:
  738. LogConfigs[i] = log.DiscordConfig{
  739. Level: level,
  740. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  741. URL: sec.Key("URL").String(),
  742. Username: sec.Key("USERNAME").String(),
  743. }
  744. }
  745. log.New(log.MODE(mode), LogConfigs[i])
  746. log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(name))
  747. }
  748. // Make sure everyone gets version info printed.
  749. log.Info("%s %s", AppName, AppVer)
  750. if !hasConsole {
  751. log.Delete(log.CONSOLE)
  752. }
  753. }
  754. func newCacheService() {
  755. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  756. switch CacheAdapter {
  757. case "memory":
  758. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  759. case "redis", "memcache":
  760. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  761. default:
  762. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  763. }
  764. log.Info("Cache Service Enabled")
  765. }
  766. func newSessionService() {
  767. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  768. []string{"memory", "file", "redis", "mysql"})
  769. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  770. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  771. SessionConfig.CookiePath = AppSubURL
  772. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  773. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  774. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  775. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  776. log.Info("Session Service Enabled")
  777. }
  778. // Mailer represents mail service.
  779. type Mailer struct {
  780. QueueLength int
  781. SubjectPrefix string
  782. Host string
  783. From string
  784. FromEmail string
  785. User, Passwd string
  786. DisableHelo bool
  787. HeloHostname string
  788. SkipVerify bool
  789. UseCertificate bool
  790. CertFile, KeyFile string
  791. UsePlainText bool
  792. AddPlainTextAlt bool
  793. }
  794. var (
  795. MailService *Mailer
  796. )
  797. // newMailService initializes mail service options from configuration.
  798. // No non-error log will be printed in hook mode.
  799. func newMailService() {
  800. sec := Cfg.Section("mailer")
  801. if !sec.Key("ENABLED").MustBool() {
  802. return
  803. }
  804. MailService = &Mailer{
  805. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  806. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  807. Host: sec.Key("HOST").String(),
  808. User: sec.Key("USER").String(),
  809. Passwd: sec.Key("PASSWD").String(),
  810. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  811. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  812. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  813. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  814. CertFile: sec.Key("CERT_FILE").String(),
  815. KeyFile: sec.Key("KEY_FILE").String(),
  816. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  817. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  818. }
  819. MailService.From = sec.Key("FROM").MustString(MailService.User)
  820. if len(MailService.From) > 0 {
  821. parsed, err := mail.ParseAddress(MailService.From)
  822. if err != nil {
  823. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  824. }
  825. MailService.FromEmail = parsed.Address
  826. }
  827. if HookMode {
  828. return
  829. }
  830. log.Info("Mail Service Enabled")
  831. }
  832. func newRegisterMailService() {
  833. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  834. return
  835. } else if MailService == nil {
  836. log.Warn("Register Mail Service: Mail Service is not enabled")
  837. return
  838. }
  839. Service.RegisterEmailConfirm = true
  840. log.Info("Register Mail Service Enabled")
  841. }
  842. // newNotifyMailService initializes notification email service options from configuration.
  843. // No non-error log will be printed in hook mode.
  844. func newNotifyMailService() {
  845. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  846. return
  847. } else if MailService == nil {
  848. log.Warn("Notify Mail Service: Mail Service is not enabled")
  849. return
  850. }
  851. Service.EnableNotifyMail = true
  852. if HookMode {
  853. return
  854. }
  855. log.Info("Notify Mail Service Enabled")
  856. }
  857. func NewService() {
  858. newService()
  859. }
  860. func NewServices() {
  861. newService()
  862. newLogService()
  863. newCacheService()
  864. newSessionService()
  865. newMailService()
  866. newRegisterMailService()
  867. newNotifyMailService()
  868. }
  869. // HookMode indicates whether program starts as Git server-side hook callback.
  870. var HookMode bool
  871. // NewPostReceiveHookServices initializes all services that are needed by
  872. // Git server-side post-receive hook callback.
  873. func NewPostReceiveHookServices() {
  874. HookMode = true
  875. newService()
  876. newMailService()
  877. newNotifyMailService()
  878. }