Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

setting.go 33KB

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