setting.go 28 KB

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