setting.go 28 KB

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