You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. "fmt"
  7. "net/mail"
  8. "net/url"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/user"
  19. "github.com/Unknwon/com"
  20. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  21. _ "github.com/go-macaron/cache/redis"
  22. "github.com/go-macaron/session"
  23. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  24. _ "github.com/kardianos/minwinsvc" // import minwinsvc for windows services
  25. "gopkg.in/ini.v1"
  26. "strk.kbt.io/projects/go/libravatar"
  27. )
  28. // Scheme describes protocol types
  29. type Scheme string
  30. // enumerates all the scheme types
  31. const (
  32. HTTP Scheme = "http"
  33. HTTPS Scheme = "https"
  34. FCGI Scheme = "fcgi"
  35. UnixSocket Scheme = "unix"
  36. )
  37. // LandingPage describes the default page
  38. type LandingPage string
  39. // enumerates all the landing page types
  40. const (
  41. LandingPageHome LandingPage = "/"
  42. LandingPageExplore LandingPage = "/explore"
  43. )
  44. // settings
  45. var (
  46. // AppVer settings
  47. AppVer string
  48. AppName string
  49. AppURL string
  50. AppSubURL string
  51. AppSubURLDepth int // Number of slashes
  52. AppPath string
  53. AppDataPath string
  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. StaticRootPath string
  65. EnableGzip bool
  66. LandingPageURL LandingPage
  67. UnixSocketPermission uint32
  68. SSH struct {
  69. Disabled bool `ini:"DISABLE_SSH"`
  70. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  71. Domain string `ini:"SSH_DOMAIN"`
  72. Port int `ini:"SSH_PORT"`
  73. ListenHost string `ini:"SSH_LISTEN_HOST"`
  74. ListenPort int `ini:"SSH_LISTEN_PORT"`
  75. RootPath string `ini:"SSH_ROOT_PATH"`
  76. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  77. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  78. MinimumKeySizeCheck bool `ini:"-"`
  79. MinimumKeySizes map[string]int `ini:"-"`
  80. }
  81. // Security settings
  82. InstallLock bool
  83. SecretKey string
  84. LogInRememberDays int
  85. CookieUserName string
  86. CookieRememberName string
  87. ReverseProxyAuthUser string
  88. // Database settings
  89. UseSQLite3 bool
  90. UseMySQL bool
  91. UseMSSQL bool
  92. UsePostgreSQL bool
  93. UseTiDB bool
  94. // Webhook settings
  95. Webhook = struct {
  96. QueueLength int
  97. DeliverTimeout int
  98. SkipTLSVerify bool
  99. Types []string
  100. PagingNum int
  101. }{
  102. QueueLength: 1000,
  103. DeliverTimeout: 5,
  104. SkipTLSVerify: false,
  105. PagingNum: 10,
  106. }
  107. // Repository settings
  108. Repository = struct {
  109. AnsiCharset string
  110. ForcePrivate bool
  111. MaxCreationLimit int
  112. MirrorQueueLength int
  113. PullRequestQueueLength int
  114. PreferredLicenses []string
  115. DisableHTTPGit bool
  116. // Repository editor settings
  117. Editor struct {
  118. LineWrapExtensions []string
  119. PreviewableFileModes []string
  120. } `ini:"-"`
  121. // Repository upload settings
  122. Upload struct {
  123. Enabled bool
  124. TempPath string
  125. AllowedTypes []string `delim:"|"`
  126. FileMaxSize int64
  127. MaxFiles int
  128. } `ini:"-"`
  129. }{
  130. AnsiCharset: "",
  131. ForcePrivate: false,
  132. MaxCreationLimit: -1,
  133. MirrorQueueLength: 1000,
  134. PullRequestQueueLength: 1000,
  135. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  136. DisableHTTPGit: false,
  137. // Repository editor settings
  138. Editor: struct {
  139. LineWrapExtensions []string
  140. PreviewableFileModes []string
  141. }{
  142. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  143. PreviewableFileModes: []string{"markdown"},
  144. },
  145. // Repository upload settings
  146. Upload: struct {
  147. Enabled bool
  148. TempPath string
  149. AllowedTypes []string `delim:"|"`
  150. FileMaxSize int64
  151. MaxFiles int
  152. }{
  153. Enabled: true,
  154. TempPath: "data/tmp/uploads",
  155. AllowedTypes: []string{},
  156. FileMaxSize: 3,
  157. MaxFiles: 5,
  158. },
  159. }
  160. RepoRootPath string
  161. ScriptType = "bash"
  162. // UI settings
  163. UI = struct {
  164. ExplorePagingNum int
  165. IssuePagingNum int
  166. FeedMaxCommitNum int
  167. ThemeColorMetaTag string
  168. MaxDisplayFileSize int64
  169. Admin struct {
  170. UserPagingNum int
  171. RepoPagingNum int
  172. NoticePagingNum int
  173. OrgPagingNum int
  174. } `ini:"ui.admin"`
  175. User struct {
  176. RepoPagingNum int
  177. } `ini:"ui.user"`
  178. }{
  179. ExplorePagingNum: 20,
  180. IssuePagingNum: 10,
  181. FeedMaxCommitNum: 5,
  182. ThemeColorMetaTag: `#6cc644`,
  183. MaxDisplayFileSize: 8388608,
  184. Admin: struct {
  185. UserPagingNum int
  186. RepoPagingNum int
  187. NoticePagingNum int
  188. OrgPagingNum int
  189. }{
  190. UserPagingNum: 50,
  191. RepoPagingNum: 50,
  192. NoticePagingNum: 25,
  193. OrgPagingNum: 50,
  194. },
  195. User: struct {
  196. RepoPagingNum int
  197. }{
  198. RepoPagingNum: 15,
  199. },
  200. }
  201. // Markdown sttings
  202. Markdown = struct {
  203. EnableHardLineBreak bool
  204. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  205. FileExtensions []string
  206. }{
  207. EnableHardLineBreak: false,
  208. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  209. }
  210. // Picture settings
  211. AvatarUploadPath string
  212. GravatarSource string
  213. DisableGravatar bool
  214. EnableFederatedAvatar bool
  215. LibravatarService *libravatar.Libravatar
  216. // Log settings
  217. LogRootPath string
  218. LogModes []string
  219. LogConfigs []string
  220. // Attachment settings
  221. AttachmentPath string
  222. AttachmentAllowedTypes string
  223. AttachmentMaxSize int64
  224. AttachmentMaxFiles int
  225. AttachmentEnabled bool
  226. // Time settings
  227. TimeFormat string
  228. // Cache settings
  229. CacheAdapter string
  230. CacheInterval int
  231. CacheConn string
  232. // Session settings
  233. SessionConfig session.Options
  234. CSRFCookieName = "_csrf"
  235. // Cron tasks
  236. Cron = struct {
  237. UpdateMirror struct {
  238. Enabled bool
  239. RunAtStart bool
  240. Schedule string
  241. } `ini:"cron.update_mirrors"`
  242. RepoHealthCheck struct {
  243. Enabled bool
  244. RunAtStart bool
  245. Schedule string
  246. Timeout time.Duration
  247. Args []string `delim:" "`
  248. } `ini:"cron.repo_health_check"`
  249. CheckRepoStats struct {
  250. Enabled bool
  251. RunAtStart bool
  252. Schedule string
  253. } `ini:"cron.check_repo_stats"`
  254. }{
  255. UpdateMirror: struct {
  256. Enabled bool
  257. RunAtStart bool
  258. Schedule string
  259. }{
  260. Schedule: "@every 10m",
  261. },
  262. RepoHealthCheck: struct {
  263. Enabled bool
  264. RunAtStart bool
  265. Schedule string
  266. Timeout time.Duration
  267. Args []string `delim:" "`
  268. }{
  269. Schedule: "@every 24h",
  270. Timeout: 60 * time.Second,
  271. Args: []string{},
  272. },
  273. CheckRepoStats: struct {
  274. Enabled bool
  275. RunAtStart bool
  276. Schedule string
  277. }{
  278. RunAtStart: true,
  279. Schedule: "@every 24h",
  280. },
  281. }
  282. // Git settings
  283. Git = struct {
  284. DisableDiffHighlight bool
  285. MaxGitDiffLines int
  286. MaxGitDiffLineCharacters int
  287. MaxGitDiffFiles int
  288. GCArgs []string `delim:" "`
  289. Timeout struct {
  290. Migrate int
  291. Mirror int
  292. Clone int
  293. Pull int
  294. GC int `ini:"GC"`
  295. } `ini:"git.timeout"`
  296. }{
  297. DisableDiffHighlight: false,
  298. MaxGitDiffLines: 1000,
  299. MaxGitDiffLineCharacters: 500,
  300. MaxGitDiffFiles: 100,
  301. GCArgs: []string{},
  302. Timeout: struct {
  303. Migrate int
  304. Mirror int
  305. Clone int
  306. Pull int
  307. GC int `ini:"GC"`
  308. }{
  309. Migrate: 600,
  310. Mirror: 300,
  311. Clone: 300,
  312. Pull: 300,
  313. GC: 60,
  314. },
  315. }
  316. // Mirror settings
  317. Mirror = struct {
  318. DefaultInterval int
  319. }{
  320. DefaultInterval: 8,
  321. }
  322. // API settings
  323. API = struct {
  324. MaxResponseItems int
  325. }{
  326. MaxResponseItems: 50,
  327. }
  328. // I18n settings
  329. Langs []string
  330. Names []string
  331. dateLangs map[string]string
  332. // Highlight settings are loaded in modules/template/hightlight.go
  333. // Other settings
  334. ShowFooterBranding bool
  335. ShowFooterVersion bool
  336. ShowFooterTemplateLoadTime bool
  337. // Global setting objects
  338. Cfg *ini.File
  339. CustomPath string // Custom directory path
  340. CustomConf string
  341. ProdMode bool
  342. RunUser string
  343. IsWindows bool
  344. HasRobotsTxt bool
  345. )
  346. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  347. func DateLang(lang string) string {
  348. name, ok := dateLangs[lang]
  349. if ok {
  350. return name
  351. }
  352. return "en"
  353. }
  354. // execPath returns the executable path.
  355. func execPath() (string, error) {
  356. file, err := exec.LookPath(os.Args[0])
  357. if err != nil {
  358. return "", err
  359. }
  360. return filepath.Abs(file)
  361. }
  362. func init() {
  363. IsWindows = runtime.GOOS == "windows"
  364. log.NewLogger(0, "console", `{"level": 0}`)
  365. var err error
  366. if AppPath, err = execPath(); err != nil {
  367. log.Fatal(4, "fail to get app path: %v\n", err)
  368. }
  369. // Note: we don't use path.Dir here because it does not handle case
  370. // which path starts with two "/" in Windows: "//psf/Home/..."
  371. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  372. }
  373. // WorkDir returns absolute path of work directory.
  374. func WorkDir() (string, error) {
  375. wd := os.Getenv("GITEA_WORK_DIR")
  376. if len(wd) > 0 {
  377. return wd, nil
  378. }
  379. // Use GOGS_WORK_DIR if available, for backward compatibility
  380. // TODO: drop in 1.1.0 ?
  381. wd = os.Getenv("GOGS_WORK_DIR")
  382. if len(wd) > 0 {
  383. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  384. please consider changing to GITEA_WORK_DIR`)
  385. return wd, nil
  386. }
  387. i := strings.LastIndex(AppPath, "/")
  388. if i == -1 {
  389. return AppPath, nil
  390. }
  391. return AppPath[:i], nil
  392. }
  393. func forcePathSeparator(path string) {
  394. if strings.Contains(path, "\\") {
  395. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  396. }
  397. }
  398. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  399. // actual user that runs the app. The first return value is the actual user name.
  400. // This check is ignored under Windows since SSH remote login is not the main
  401. // method to login on Windows.
  402. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  403. if IsWindows {
  404. return "", true
  405. }
  406. currentUser := user.CurrentUsername()
  407. return currentUser, runUser == currentUser
  408. }
  409. // NewContext initializes configuration context.
  410. // NOTE: do not print any log except error.
  411. func NewContext() {
  412. workDir, err := WorkDir()
  413. if err != nil {
  414. log.Fatal(4, "Fail to get work directory: %v", err)
  415. }
  416. Cfg = ini.Empty()
  417. if err != nil {
  418. log.Fatal(4, "Fail to parse 'app.ini': %v", err)
  419. }
  420. CustomPath = os.Getenv("GITEA_CUSTOM")
  421. if len(CustomPath) == 0 {
  422. // For backward compatibility
  423. // TODO: drop in 1.1.0 ?
  424. CustomPath = os.Getenv("GOGS_CUSTOM")
  425. if len(CustomPath) == 0 {
  426. CustomPath = workDir + "/custom"
  427. } else {
  428. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  429. please consider changing to GITEA_CUSTOM`)
  430. }
  431. }
  432. if len(CustomConf) == 0 {
  433. CustomConf = CustomPath + "/conf/app.ini"
  434. }
  435. if com.IsFile(CustomConf) {
  436. if err = Cfg.Append(CustomConf); err != nil {
  437. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  438. }
  439. } else {
  440. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  441. }
  442. Cfg.NameMapper = ini.AllCapsUnderscore
  443. homeDir, err := com.HomeDir()
  444. if err != nil {
  445. log.Fatal(4, "Fail to get home directory: %v", err)
  446. }
  447. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  448. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  449. forcePathSeparator(LogRootPath)
  450. sec := Cfg.Section("server")
  451. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  452. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  453. if AppURL[len(AppURL)-1] != '/' {
  454. AppURL += "/"
  455. }
  456. // Check if has app suburl.
  457. url, err := url.Parse(AppURL)
  458. if err != nil {
  459. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  460. }
  461. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  462. // This value is empty if site does not have sub-url.
  463. AppSubURL = strings.TrimSuffix(url.Path, "/")
  464. AppSubURLDepth = strings.Count(AppSubURL, "/")
  465. Protocol = HTTP
  466. if sec.Key("PROTOCOL").String() == "https" {
  467. Protocol = HTTPS
  468. CertFile = sec.Key("CERT_FILE").String()
  469. KeyFile = sec.Key("KEY_FILE").String()
  470. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  471. Protocol = FCGI
  472. } else if sec.Key("PROTOCOL").String() == "unix" {
  473. Protocol = UnixSocket
  474. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  475. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  476. if err != nil || UnixSocketPermissionParsed > 0777 {
  477. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  478. }
  479. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  480. }
  481. Domain = sec.Key("DOMAIN").MustString("localhost")
  482. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  483. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  484. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  485. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  486. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  487. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  488. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  489. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  490. switch sec.Key("LANDING_PAGE").MustString("home") {
  491. case "explore":
  492. LandingPageURL = LandingPageExplore
  493. default:
  494. LandingPageURL = LandingPageHome
  495. }
  496. SSH.RootPath = path.Join(homeDir, ".ssh")
  497. SSH.KeyTestPath = os.TempDir()
  498. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  499. log.Fatal(4, "Fail to map SSH settings: %v", err)
  500. }
  501. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  502. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  503. // When disable SSH, start builtin server value is ignored.
  504. if SSH.Disabled {
  505. SSH.StartBuiltinServer = false
  506. }
  507. if !SSH.Disabled && !SSH.StartBuiltinServer {
  508. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  509. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  510. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  511. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  512. }
  513. }
  514. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  515. SSH.MinimumKeySizes = map[string]int{}
  516. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  517. for _, key := range minimumKeySizes {
  518. if key.MustInt() != -1 {
  519. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  520. }
  521. }
  522. sec = Cfg.Section("security")
  523. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  524. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  525. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  526. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  527. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  528. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  529. sec = Cfg.Section("attachment")
  530. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  531. if !filepath.IsAbs(AttachmentPath) {
  532. AttachmentPath = path.Join(workDir, AttachmentPath)
  533. }
  534. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  535. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  536. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  537. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  538. TimeFormat = map[string]string{
  539. "ANSIC": time.ANSIC,
  540. "UnixDate": time.UnixDate,
  541. "RubyDate": time.RubyDate,
  542. "RFC822": time.RFC822,
  543. "RFC822Z": time.RFC822Z,
  544. "RFC850": time.RFC850,
  545. "RFC1123": time.RFC1123,
  546. "RFC1123Z": time.RFC1123Z,
  547. "RFC3339": time.RFC3339,
  548. "RFC3339Nano": time.RFC3339Nano,
  549. "Kitchen": time.Kitchen,
  550. "Stamp": time.Stamp,
  551. "StampMilli": time.StampMilli,
  552. "StampMicro": time.StampMicro,
  553. "StampNano": time.StampNano,
  554. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  555. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  556. // Does not check run user when the install lock is off.
  557. if InstallLock {
  558. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  559. if !match {
  560. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  561. }
  562. }
  563. // Determine and create root git repository path.
  564. sec = Cfg.Section("repository")
  565. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  566. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  567. forcePathSeparator(RepoRootPath)
  568. if !filepath.IsAbs(RepoRootPath) {
  569. RepoRootPath = path.Join(workDir, RepoRootPath)
  570. } else {
  571. RepoRootPath = path.Clean(RepoRootPath)
  572. }
  573. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  574. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  575. log.Fatal(4, "Fail to map Repository settings: %v", err)
  576. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  577. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  578. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  579. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  580. }
  581. if !filepath.IsAbs(Repository.Upload.TempPath) {
  582. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  583. }
  584. sec = Cfg.Section("picture")
  585. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  586. forcePathSeparator(AvatarUploadPath)
  587. if !filepath.IsAbs(AvatarUploadPath) {
  588. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  589. }
  590. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  591. case "duoshuo":
  592. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  593. case "gravatar":
  594. GravatarSource = "https://secure.gravatar.com/avatar/"
  595. case "libravatar":
  596. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  597. default:
  598. GravatarSource = source
  599. }
  600. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  601. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  602. if OfflineMode {
  603. DisableGravatar = true
  604. EnableFederatedAvatar = false
  605. }
  606. if DisableGravatar {
  607. EnableFederatedAvatar = false
  608. }
  609. if EnableFederatedAvatar {
  610. LibravatarService = libravatar.New()
  611. parts := strings.Split(GravatarSource, "/")
  612. if len(parts) >= 3 {
  613. if parts[0] == "https:" {
  614. LibravatarService.SetUseHTTPS(true)
  615. LibravatarService.SetSecureFallbackHost(parts[2])
  616. } else {
  617. LibravatarService.SetUseHTTPS(false)
  618. LibravatarService.SetFallbackHost(parts[2])
  619. }
  620. }
  621. }
  622. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  623. log.Fatal(4, "Fail to map UI settings: %v", err)
  624. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  625. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  626. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  627. log.Fatal(4, "Fail to map Cron settings: %v", err)
  628. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  629. log.Fatal(4, "Fail to map Git settings: %v", err)
  630. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  631. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  632. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  633. log.Fatal(4, "Fail to map API settings: %v", err)
  634. }
  635. if Mirror.DefaultInterval <= 0 {
  636. Mirror.DefaultInterval = 24
  637. }
  638. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  639. if len(Langs) == 0 {
  640. Langs = defaultLangs
  641. }
  642. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  643. if len(Names) == 0 {
  644. Names = defaultLangNames
  645. }
  646. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  647. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  648. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  649. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  650. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  651. }
  652. // Service settings
  653. var Service struct {
  654. ActiveCodeLives int
  655. ResetPwdCodeLives int
  656. RegisterEmailConfirm bool
  657. DisableRegistration bool
  658. ShowRegistrationButton bool
  659. RequireSignInView bool
  660. EnableNotifyMail bool
  661. EnableReverseProxyAuth bool
  662. EnableReverseProxyAutoRegister bool
  663. EnableCaptcha bool
  664. }
  665. func newService() {
  666. sec := Cfg.Section("service")
  667. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  668. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  669. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  670. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  671. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  672. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  673. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  674. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  675. }
  676. var logLevels = map[string]string{
  677. "Trace": "0",
  678. "Debug": "1",
  679. "Info": "2",
  680. "Warn": "3",
  681. "Error": "4",
  682. "Critical": "5",
  683. }
  684. func newLogService() {
  685. log.Info("Gitea v%s", AppVer)
  686. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  687. LogConfigs = make([]string, len(LogModes))
  688. for i, mode := range LogModes {
  689. mode = strings.TrimSpace(mode)
  690. sec, err := Cfg.GetSection("log." + mode)
  691. if err != nil {
  692. sec, _ = Cfg.NewSection("log." + mode)
  693. }
  694. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  695. // Log level.
  696. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  697. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  698. validLevels)
  699. level, ok := logLevels[levelName]
  700. if !ok {
  701. log.Fatal(4, "Unknown log level: %s", levelName)
  702. }
  703. // Generate log configuration.
  704. switch mode {
  705. case "console":
  706. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  707. case "file":
  708. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  709. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  710. panic(err.Error())
  711. }
  712. LogConfigs[i] = fmt.Sprintf(
  713. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  714. logPath,
  715. sec.Key("LOG_ROTATE").MustBool(true),
  716. sec.Key("MAX_LINES").MustInt(1000000),
  717. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  718. sec.Key("DAILY_ROTATE").MustBool(true),
  719. sec.Key("MAX_DAYS").MustInt(7))
  720. case "conn":
  721. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  722. sec.Key("RECONNECT_ON_MSG").MustBool(),
  723. sec.Key("RECONNECT").MustBool(),
  724. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  725. sec.Key("ADDR").MustString(":7020"))
  726. case "smtp":
  727. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  728. sec.Key("USER").MustString("example@example.com"),
  729. sec.Key("PASSWD").MustString("******"),
  730. sec.Key("HOST").MustString("127.0.0.1:25"),
  731. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  732. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  733. case "database":
  734. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  735. sec.Key("DRIVER").String(),
  736. sec.Key("CONN").String())
  737. }
  738. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  739. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  740. }
  741. }
  742. func newCacheService() {
  743. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  744. switch CacheAdapter {
  745. case "memory":
  746. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  747. case "redis", "memcache":
  748. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  749. default:
  750. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  751. }
  752. log.Info("Cache Service Enabled")
  753. }
  754. func newSessionService() {
  755. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  756. []string{"memory", "file", "redis", "mysql"})
  757. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  758. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  759. SessionConfig.CookiePath = AppSubURL
  760. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  761. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  762. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  763. log.Info("Session Service Enabled")
  764. }
  765. // Mailer represents mail service.
  766. type Mailer struct {
  767. QueueLength int
  768. Name string
  769. Host string
  770. From string
  771. FromEmail string
  772. User, Passwd string
  773. DisableHelo bool
  774. HeloHostname string
  775. SkipVerify bool
  776. UseCertificate bool
  777. CertFile, KeyFile string
  778. EnableHTMLAlternative bool
  779. }
  780. var (
  781. // MailService the global mailer
  782. MailService *Mailer
  783. )
  784. func newMailService() {
  785. sec := Cfg.Section("mailer")
  786. // Check mailer setting.
  787. if !sec.Key("ENABLED").MustBool() {
  788. return
  789. }
  790. MailService = &Mailer{
  791. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  792. Name: sec.Key("NAME").MustString(AppName),
  793. Host: sec.Key("HOST").String(),
  794. User: sec.Key("USER").String(),
  795. Passwd: sec.Key("PASSWD").String(),
  796. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  797. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  798. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  799. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  800. CertFile: sec.Key("CERT_FILE").String(),
  801. KeyFile: sec.Key("KEY_FILE").String(),
  802. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  803. }
  804. MailService.From = sec.Key("FROM").MustString(MailService.User)
  805. parsed, err := mail.ParseAddress(MailService.From)
  806. if err != nil {
  807. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  808. }
  809. MailService.FromEmail = parsed.Address
  810. log.Info("Mail Service Enabled")
  811. }
  812. func newRegisterMailService() {
  813. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  814. return
  815. } else if MailService == nil {
  816. log.Warn("Register Mail Service: Mail Service is not enabled")
  817. return
  818. }
  819. Service.RegisterEmailConfirm = true
  820. log.Info("Register Mail Service Enabled")
  821. }
  822. func newNotifyMailService() {
  823. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  824. return
  825. } else if MailService == nil {
  826. log.Warn("Notify Mail Service: Mail Service is not enabled")
  827. return
  828. }
  829. Service.EnableNotifyMail = true
  830. log.Info("Notify Mail Service Enabled")
  831. }
  832. func newWebhookService() {
  833. sec := Cfg.Section("webhook")
  834. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  835. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  836. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  837. Webhook.Types = []string{"gogs", "slack"}
  838. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  839. }
  840. // NewServices initializes the services
  841. func NewServices() {
  842. newService()
  843. newLogService()
  844. newCacheService()
  845. newSessionService()
  846. newMailService()
  847. newRegisterMailService()
  848. newNotifyMailService()
  849. newWebhookService()
  850. }