setting.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. )
  291. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  292. func DateLang(lang string) string {
  293. name, ok := dateLangs[lang]
  294. if ok {
  295. return name
  296. }
  297. return "en"
  298. }
  299. // execPath returns the executable path.
  300. func execPath() (string, error) {
  301. file, err := exec.LookPath(os.Args[0])
  302. if err != nil {
  303. return "", err
  304. }
  305. return filepath.Abs(file)
  306. }
  307. func init() {
  308. IsWindows = runtime.GOOS == "windows"
  309. log.New(log.CONSOLE, log.ConsoleConfig{})
  310. var err error
  311. if AppPath, err = execPath(); err != nil {
  312. log.Fatal(2, "Fail to get app path: %v\n", err)
  313. }
  314. // Note: we don't use path.Dir here because it does not handle case
  315. // which path starts with two "/" in Windows: "//psf/Home/..."
  316. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  317. }
  318. // WorkDir returns absolute path of work directory.
  319. func WorkDir() (string, error) {
  320. wd := os.Getenv("GOGS_WORK_DIR")
  321. if len(wd) > 0 {
  322. return wd, nil
  323. }
  324. i := strings.LastIndex(AppPath, "/")
  325. if i == -1 {
  326. return AppPath, nil
  327. }
  328. return AppPath[:i], nil
  329. }
  330. func forcePathSeparator(path string) {
  331. if strings.Contains(path, "\\") {
  332. log.Fatal(2, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  333. }
  334. }
  335. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  336. // actual user that runs the app. The first return value is the actual user name.
  337. // This check is ignored under Windows since SSH remote login is not the main
  338. // method to login on Windows.
  339. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  340. if IsWindows {
  341. return "", true
  342. }
  343. currentUser := user.CurrentUsername()
  344. return currentUser, runUser == currentUser
  345. }
  346. // getOpenSSHVersion parses and returns string representation of OpenSSH version
  347. // returned by command "ssh -V".
  348. func getOpenSSHVersion() string {
  349. // Note: somehow version is printed to stderr
  350. _, stderr, err := process.Exec("getOpenSSHVersion", "ssh", "-V")
  351. if err != nil {
  352. log.Fatal(2, "Fail to get OpenSSH version: %v - %s", err, stderr)
  353. }
  354. // Trim unused information: https://github.com/gogs/gogs/issues/4507#issuecomment-305150441
  355. version := strings.TrimRight(strings.Fields(stderr)[0], ",1234567890")
  356. version = strings.TrimSuffix(strings.TrimPrefix(version, "OpenSSH_"), "p")
  357. return version
  358. }
  359. // NewContext initializes configuration context.
  360. // NOTE: do not print any log except error.
  361. func NewContext() {
  362. workDir, err := WorkDir()
  363. if err != nil {
  364. log.Fatal(2, "Fail to get work directory: %v", err)
  365. }
  366. Cfg, err = ini.LoadSources(ini.LoadOptions{
  367. IgnoreInlineComment: true,
  368. }, bindata.MustAsset("conf/app.ini"))
  369. if err != nil {
  370. log.Fatal(2, "Fail to parse 'conf/app.ini': %v", err)
  371. }
  372. CustomPath = os.Getenv("GOGS_CUSTOM")
  373. if len(CustomPath) == 0 {
  374. CustomPath = workDir + "/custom"
  375. }
  376. if len(CustomConf) == 0 {
  377. CustomConf = CustomPath + "/conf/app.ini"
  378. }
  379. if com.IsFile(CustomConf) {
  380. if err = Cfg.Append(CustomConf); err != nil {
  381. log.Fatal(2, "Fail to load custom conf '%s': %v", CustomConf, err)
  382. }
  383. } else {
  384. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  385. }
  386. Cfg.NameMapper = ini.AllCapsUnderscore
  387. homeDir, err := com.HomeDir()
  388. if err != nil {
  389. log.Fatal(2, "Fail to get home directory: %v", err)
  390. }
  391. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  392. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  393. forcePathSeparator(LogRootPath)
  394. sec := Cfg.Section("server")
  395. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs")
  396. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  397. if AppURL[len(AppURL)-1] != '/' {
  398. AppURL += "/"
  399. }
  400. // Check if has app suburl.
  401. url, err := url.Parse(AppURL)
  402. if err != nil {
  403. log.Fatal(2, "Invalid ROOT_URL '%s': %s", AppURL, err)
  404. }
  405. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  406. // This value is empty if site does not have sub-url.
  407. AppSubURL = strings.TrimSuffix(url.Path, "/")
  408. AppSubURLDepth = strings.Count(AppSubURL, "/")
  409. HostAddress = url.Host
  410. Protocol = SCHEME_HTTP
  411. if sec.Key("PROTOCOL").String() == "https" {
  412. Protocol = SCHEME_HTTPS
  413. CertFile = sec.Key("CERT_FILE").String()
  414. KeyFile = sec.Key("KEY_FILE").String()
  415. TLSMinVersion = sec.Key("TLS_MIN_VERSION").String()
  416. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  417. Protocol = SCHEME_FCGI
  418. } else if sec.Key("PROTOCOL").String() == "unix" {
  419. Protocol = SCHEME_UNIX_SOCKET
  420. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  421. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  422. if err != nil || UnixSocketPermissionParsed > 0777 {
  423. log.Fatal(2, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  424. }
  425. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  426. }
  427. Domain = sec.Key("DOMAIN").MustString("localhost")
  428. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  429. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  430. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  431. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  432. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  433. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  434. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  435. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  436. switch sec.Key("LANDING_PAGE").MustString("home") {
  437. case "explore":
  438. LandingPageURL = LANDING_PAGE_EXPLORE
  439. default:
  440. LandingPageURL = LANDING_PAGE_HOME
  441. }
  442. SSH.RootPath = path.Join(homeDir, ".ssh")
  443. SSH.RewriteAuthorizedKeysAtStart = sec.Key("REWRITE_AUTHORIZED_KEYS_AT_START").MustBool()
  444. SSH.ServerCiphers = sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  445. SSH.KeyTestPath = os.TempDir()
  446. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  447. log.Fatal(2, "Fail to map SSH settings: %v", err)
  448. }
  449. if SSH.Disabled {
  450. SSH.StartBuiltinServer = false
  451. SSH.MinimumKeySizeCheck = false
  452. }
  453. if !SSH.Disabled && !SSH.StartBuiltinServer {
  454. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  455. log.Fatal(2, "Fail to create '%s': %v", SSH.RootPath, err)
  456. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  457. log.Fatal(2, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  458. }
  459. }
  460. if SSH.StartBuiltinServer {
  461. SSH.RewriteAuthorizedKeysAtStart = false
  462. }
  463. // Check if server is eligible for minimum key size check when user choose to enable.
  464. // Windows server and OpenSSH version lower than 5.1 (https://github.com/gogs/gogs/issues/4507)
  465. // are forced to be disabled because the "ssh-keygen" in Windows does not print key type.
  466. if SSH.MinimumKeySizeCheck &&
  467. (IsWindows || version.Compare(getOpenSSHVersion(), "5.1", "<")) {
  468. SSH.MinimumKeySizeCheck = false
  469. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  470. 1. Windows server
  471. 2. OpenSSH version is lower than 5.1`)
  472. }
  473. if SSH.MinimumKeySizeCheck {
  474. SSH.MinimumKeySizes = map[string]int{}
  475. for _, key := range Cfg.Section("ssh.minimum_key_sizes").Keys() {
  476. if key.MustInt() != -1 {
  477. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  478. }
  479. }
  480. }
  481. sec = Cfg.Section("security")
  482. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  483. SecretKey = sec.Key("SECRET_KEY").String()
  484. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  485. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  486. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  487. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  488. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  489. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  490. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  491. sec = Cfg.Section("attachment")
  492. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  493. if !filepath.IsAbs(AttachmentPath) {
  494. AttachmentPath = path.Join(workDir, AttachmentPath)
  495. }
  496. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  497. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  498. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  499. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  500. TimeFormat = map[string]string{
  501. "ANSIC": time.ANSIC,
  502. "UnixDate": time.UnixDate,
  503. "RubyDate": time.RubyDate,
  504. "RFC822": time.RFC822,
  505. "RFC822Z": time.RFC822Z,
  506. "RFC850": time.RFC850,
  507. "RFC1123": time.RFC1123,
  508. "RFC1123Z": time.RFC1123Z,
  509. "RFC3339": time.RFC3339,
  510. "RFC3339Nano": time.RFC3339Nano,
  511. "Kitchen": time.Kitchen,
  512. "Stamp": time.Stamp,
  513. "StampMilli": time.StampMilli,
  514. "StampMicro": time.StampMicro,
  515. "StampNano": time.StampNano,
  516. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  517. RunUser = Cfg.Section("").Key("RUN_USER").String()
  518. // Does not check run user when the install lock is off.
  519. if InstallLock {
  520. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  521. if !match {
  522. log.Fatal(2, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  523. }
  524. }
  525. ProdMode = Cfg.Section("").Key("RUN_MODE").String() == "prod"
  526. // Determine and create root git repository path.
  527. sec = Cfg.Section("repository")
  528. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  529. forcePathSeparator(RepoRootPath)
  530. if !filepath.IsAbs(RepoRootPath) {
  531. RepoRootPath = path.Join(workDir, RepoRootPath)
  532. } else {
  533. RepoRootPath = path.Clean(RepoRootPath)
  534. }
  535. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  536. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  537. log.Fatal(2, "Fail to map Repository settings: %v", err)
  538. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  539. log.Fatal(2, "Fail to map Repository.Editor settings: %v", err)
  540. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  541. log.Fatal(2, "Fail to map Repository.Upload settings: %v", err)
  542. }
  543. if !filepath.IsAbs(Repository.Upload.TempPath) {
  544. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  545. }
  546. sec = Cfg.Section("picture")
  547. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  548. forcePathSeparator(AvatarUploadPath)
  549. if !filepath.IsAbs(AvatarUploadPath) {
  550. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  551. }
  552. RepositoryAvatarUploadPath = sec.Key("REPOSITORY_AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "repo-avatars"))
  553. forcePathSeparator(RepositoryAvatarUploadPath)
  554. if !filepath.IsAbs(RepositoryAvatarUploadPath) {
  555. RepositoryAvatarUploadPath = path.Join(workDir, RepositoryAvatarUploadPath)
  556. }
  557. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  558. case "duoshuo":
  559. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  560. case "gravatar":
  561. GravatarSource = "https://secure.gravatar.com/avatar/"
  562. case "libravatar":
  563. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  564. default:
  565. GravatarSource = source
  566. }
  567. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  568. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(true)
  569. if OfflineMode {
  570. DisableGravatar = true
  571. EnableFederatedAvatar = false
  572. }
  573. if DisableGravatar {
  574. EnableFederatedAvatar = false
  575. }
  576. if EnableFederatedAvatar {
  577. LibravatarService = libravatar.New()
  578. parts := strings.Split(GravatarSource, "/")
  579. if len(parts) >= 3 {
  580. if parts[0] == "https:" {
  581. LibravatarService.SetUseHTTPS(true)
  582. LibravatarService.SetSecureFallbackHost(parts[2])
  583. } else {
  584. LibravatarService.SetUseHTTPS(false)
  585. LibravatarService.SetFallbackHost(parts[2])
  586. }
  587. }
  588. }
  589. if err = Cfg.Section("http").MapTo(&HTTP); err != nil {
  590. log.Fatal(2, "Failed to map HTTP settings: %v", err)
  591. } else if err = Cfg.Section("webhook").MapTo(&Webhook); err != nil {
  592. log.Fatal(2, "Failed to map Webhook settings: %v", err)
  593. } else if err = Cfg.Section("release.attachment").MapTo(&Release.Attachment); err != nil {
  594. log.Fatal(2, "Failed to map Release.Attachment settings: %v", err)
  595. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  596. log.Fatal(2, "Failed to map Markdown settings: %v", err)
  597. } else if err = Cfg.Section("smartypants").MapTo(&Smartypants); err != nil {
  598. log.Fatal(2, "Failed to map Smartypants settings: %v", err)
  599. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  600. log.Fatal(2, "Failed to map Admin settings: %v", err)
  601. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  602. log.Fatal(2, "Failed to map Cron settings: %v", err)
  603. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  604. log.Fatal(2, "Failed to map Git settings: %v", err)
  605. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  606. log.Fatal(2, "Failed to map Mirror settings: %v", err)
  607. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  608. log.Fatal(2, "Failed to map API settings: %v", err)
  609. } else if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  610. log.Fatal(2, "Failed to map UI settings: %v", err)
  611. } else if err = Cfg.Section("prometheus").MapTo(&Prometheus); err != nil {
  612. log.Fatal(2, "Failed to map Prometheus settings: %v", err)
  613. }
  614. if Mirror.DefaultInterval <= 0 {
  615. Mirror.DefaultInterval = 24
  616. }
  617. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  618. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  619. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  620. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  621. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  622. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool()
  623. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  624. }
  625. var Service struct {
  626. ActiveCodeLives int
  627. ResetPwdCodeLives int
  628. RegisterEmailConfirm bool
  629. DisableRegistration bool
  630. ShowRegistrationButton bool
  631. RequireSignInView bool
  632. EnableNotifyMail bool
  633. EnableReverseProxyAuth bool
  634. EnableReverseProxyAutoRegister bool
  635. EnableCaptcha bool
  636. }
  637. func newService() {
  638. sec := Cfg.Section("service")
  639. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  640. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  641. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  642. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  643. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  644. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  645. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  646. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  647. }
  648. func newLogService() {
  649. if len(BuildTime) > 0 {
  650. log.Trace("Build Time: %s", BuildTime)
  651. log.Trace("Build Git Hash: %s", BuildGitHash)
  652. }
  653. // Because we always create a console logger as primary logger before all settings are loaded,
  654. // thus if user doesn't set console logger, we should remove it after other loggers are created.
  655. hasConsole := false
  656. // Get and check log modes.
  657. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  658. LogConfigs = make([]interface{}, len(LogModes))
  659. levelNames := map[string]log.LEVEL{
  660. "trace": log.TRACE,
  661. "info": log.INFO,
  662. "warn": log.WARN,
  663. "error": log.ERROR,
  664. "fatal": log.FATAL,
  665. }
  666. for i, mode := range LogModes {
  667. mode = strings.ToLower(strings.TrimSpace(mode))
  668. sec, err := Cfg.GetSection("log." + mode)
  669. if err != nil {
  670. log.Fatal(2, "Unknown logger mode: %s", mode)
  671. }
  672. validLevels := []string{"trace", "info", "warn", "error", "fatal"}
  673. name := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
  674. v = strings.ToLower(v)
  675. if com.IsSliceContainsStr(validLevels, v) {
  676. return v
  677. }
  678. return "trace"
  679. })
  680. level := levelNames[name]
  681. // Generate log configuration.
  682. switch log.MODE(mode) {
  683. case log.CONSOLE:
  684. hasConsole = true
  685. LogConfigs[i] = log.ConsoleConfig{
  686. Level: level,
  687. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  688. }
  689. case log.FILE:
  690. logPath := path.Join(LogRootPath, "gogs.log")
  691. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  692. log.Fatal(2, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
  693. }
  694. LogConfigs[i] = log.FileConfig{
  695. Level: level,
  696. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  697. Filename: logPath,
  698. FileRotationConfig: log.FileRotationConfig{
  699. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  700. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  701. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  702. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  703. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  704. },
  705. }
  706. case log.SLACK:
  707. LogConfigs[i] = log.SlackConfig{
  708. Level: level,
  709. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  710. URL: sec.Key("URL").String(),
  711. }
  712. case log.DISCORD:
  713. LogConfigs[i] = log.DiscordConfig{
  714. Level: level,
  715. BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
  716. URL: sec.Key("URL").String(),
  717. Username: sec.Key("USERNAME").String(),
  718. }
  719. }
  720. log.New(log.MODE(mode), LogConfigs[i])
  721. log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(name))
  722. }
  723. // Make sure everyone gets version info printed.
  724. log.Info("%s %s", AppName, AppVer)
  725. if !hasConsole {
  726. log.Delete(log.CONSOLE)
  727. }
  728. }
  729. func newCacheService() {
  730. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  731. switch CacheAdapter {
  732. case "memory":
  733. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  734. case "redis", "memcache":
  735. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  736. default:
  737. log.Fatal(2, "Unknown cache adapter: %s", CacheAdapter)
  738. }
  739. log.Info("Cache Service Enabled")
  740. }
  741. func newSessionService() {
  742. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  743. []string{"memory", "file", "redis", "mysql"})
  744. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  745. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  746. SessionConfig.CookiePath = AppSubURL
  747. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  748. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  749. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  750. CSRFCookieName = Cfg.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  751. log.Info("Session Service Enabled")
  752. }
  753. // Mailer represents mail service.
  754. type Mailer struct {
  755. QueueLength int
  756. SubjectPrefix string
  757. Host string
  758. From string
  759. FromEmail string
  760. User, Passwd string
  761. DisableHelo bool
  762. HeloHostname string
  763. SkipVerify bool
  764. UseCertificate bool
  765. CertFile, KeyFile string
  766. UsePlainText bool
  767. AddPlainTextAlt bool
  768. }
  769. var (
  770. MailService *Mailer
  771. )
  772. // newMailService initializes mail service options from configuration.
  773. // No non-error log will be printed in hook mode.
  774. func newMailService() {
  775. sec := Cfg.Section("mailer")
  776. if !sec.Key("ENABLED").MustBool() {
  777. return
  778. }
  779. MailService = &Mailer{
  780. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  781. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + AppName + "] "),
  782. Host: sec.Key("HOST").String(),
  783. User: sec.Key("USER").String(),
  784. Passwd: sec.Key("PASSWD").String(),
  785. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  786. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  787. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  788. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  789. CertFile: sec.Key("CERT_FILE").String(),
  790. KeyFile: sec.Key("KEY_FILE").String(),
  791. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  792. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  793. }
  794. MailService.From = sec.Key("FROM").MustString(MailService.User)
  795. if len(MailService.From) > 0 {
  796. parsed, err := mail.ParseAddress(MailService.From)
  797. if err != nil {
  798. log.Fatal(2, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  799. }
  800. MailService.FromEmail = parsed.Address
  801. }
  802. if HookMode {
  803. return
  804. }
  805. log.Info("Mail Service Enabled")
  806. }
  807. func newRegisterMailService() {
  808. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  809. return
  810. } else if MailService == nil {
  811. log.Warn("Register Mail Service: Mail Service is not enabled")
  812. return
  813. }
  814. Service.RegisterEmailConfirm = true
  815. log.Info("Register Mail Service Enabled")
  816. }
  817. // newNotifyMailService initializes notification email service options from configuration.
  818. // No non-error log will be printed in hook mode.
  819. func newNotifyMailService() {
  820. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  821. return
  822. } else if MailService == nil {
  823. log.Warn("Notify Mail Service: Mail Service is not enabled")
  824. return
  825. }
  826. Service.EnableNotifyMail = true
  827. if HookMode {
  828. return
  829. }
  830. log.Info("Notify Mail Service Enabled")
  831. }
  832. func NewService() {
  833. newService()
  834. }
  835. func NewServices() {
  836. newService()
  837. newLogService()
  838. newCacheService()
  839. newSessionService()
  840. newMailService()
  841. newRegisterMailService()
  842. newNotifyMailService()
  843. }
  844. // HookMode indicates whether program starts as Git server-side hook callback.
  845. var HookMode bool
  846. // NewPostReceiveHookServices initializes all services that are needed by
  847. // Git server-side post-receive hook callback.
  848. func NewPostReceiveHookServices() {
  849. HookMode = true
  850. newService()
  851. newMailService()
  852. newNotifyMailService()
  853. }