setting.go 29 KB

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