Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

setting.go 49KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "encoding/base64"
  8. "fmt"
  9. "net"
  10. "net/mail"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "code.gitea.io/git"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/log"
  24. _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
  25. "code.gitea.io/gitea/modules/user"
  26. "github.com/Unknwon/com"
  27. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  28. _ "github.com/go-macaron/cache/redis"
  29. "github.com/go-macaron/session"
  30. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  31. "github.com/go-xorm/core"
  32. "github.com/kballard/go-shellquote"
  33. "gopkg.in/ini.v1"
  34. "strk.kbt.io/projects/go/libravatar"
  35. )
  36. // Scheme describes protocol types
  37. type Scheme string
  38. // enumerates all the scheme types
  39. const (
  40. HTTP Scheme = "http"
  41. HTTPS Scheme = "https"
  42. FCGI Scheme = "fcgi"
  43. UnixSocket Scheme = "unix"
  44. )
  45. // LandingPage describes the default page
  46. type LandingPage string
  47. // enumerates all the landing page types
  48. const (
  49. LandingPageHome LandingPage = "/"
  50. LandingPageExplore LandingPage = "/explore"
  51. LandingPageOrganizations LandingPage = "/explore/organizations"
  52. )
  53. // MarkupParser defines the external parser configured in ini
  54. type MarkupParser struct {
  55. Enabled bool
  56. MarkupName string
  57. Command string
  58. FileExtensions []string
  59. IsInputFile bool
  60. }
  61. // enumerates all the policy repository creating
  62. const (
  63. RepoCreatingLastUserVisibility = "last"
  64. RepoCreatingPrivate = "private"
  65. RepoCreatingPublic = "public"
  66. )
  67. // enumerates all the types of captchas
  68. const (
  69. ImageCaptcha = "image"
  70. ReCaptcha = "recaptcha"
  71. )
  72. // settings
  73. var (
  74. // AppVer settings
  75. AppVer string
  76. AppBuiltWith string
  77. AppName string
  78. AppURL string
  79. AppSubURL string
  80. AppSubURLDepth int // Number of slashes
  81. AppPath string
  82. AppDataPath string
  83. AppWorkPath string
  84. // Server settings
  85. Protocol Scheme
  86. Domain string
  87. HTTPAddr string
  88. HTTPPort string
  89. LocalURL string
  90. RedirectOtherPort bool
  91. PortToRedirect string
  92. OfflineMode bool
  93. DisableRouterLog bool
  94. CertFile string
  95. KeyFile string
  96. StaticRootPath string
  97. EnableGzip bool
  98. LandingPageURL LandingPage
  99. UnixSocketPermission uint32
  100. EnablePprof bool
  101. PprofDataPath string
  102. EnableLetsEncrypt bool
  103. LetsEncryptTOS bool
  104. LetsEncryptDirectory string
  105. LetsEncryptEmail string
  106. SSH = struct {
  107. Disabled bool `ini:"DISABLE_SSH"`
  108. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  109. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  110. Domain string `ini:"SSH_DOMAIN"`
  111. Port int `ini:"SSH_PORT"`
  112. ListenHost string `ini:"SSH_LISTEN_HOST"`
  113. ListenPort int `ini:"SSH_LISTEN_PORT"`
  114. RootPath string `ini:"SSH_ROOT_PATH"`
  115. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  116. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  117. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  118. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  119. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  120. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  121. MinimumKeySizeCheck bool `ini:"-"`
  122. MinimumKeySizes map[string]int `ini:"-"`
  123. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  124. }{
  125. Disabled: false,
  126. StartBuiltinServer: false,
  127. Domain: "",
  128. Port: 22,
  129. ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128"},
  130. ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "curve25519-sha256@libssh.org"},
  131. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
  132. KeygenPath: "ssh-keygen",
  133. }
  134. LFS struct {
  135. StartServer bool `ini:"LFS_START_SERVER"`
  136. ContentPath string `ini:"LFS_CONTENT_PATH"`
  137. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  138. JWTSecretBytes []byte `ini:"-"`
  139. HTTPAuthExpiry time.Duration `ini:"LFS_HTTP_AUTH_EXPIRY"`
  140. }
  141. // Security settings
  142. InstallLock bool
  143. SecretKey string
  144. LogInRememberDays int
  145. CookieUserName string
  146. CookieRememberName string
  147. ReverseProxyAuthUser string
  148. MinPasswordLength int
  149. ImportLocalPaths bool
  150. DisableGitHooks bool
  151. // Database settings
  152. UseSQLite3 bool
  153. UseMySQL bool
  154. UseMSSQL bool
  155. UsePostgreSQL bool
  156. UseTiDB bool
  157. LogSQL bool
  158. // Indexer settings
  159. Indexer struct {
  160. IssuePath string
  161. RepoIndexerEnabled bool
  162. RepoPath string
  163. UpdateQueueLength int
  164. MaxIndexerFileSize int64
  165. }
  166. // Webhook settings
  167. Webhook = struct {
  168. QueueLength int
  169. DeliverTimeout int
  170. SkipTLSVerify bool
  171. Types []string
  172. PagingNum int
  173. }{
  174. QueueLength: 1000,
  175. DeliverTimeout: 5,
  176. SkipTLSVerify: false,
  177. PagingNum: 10,
  178. }
  179. // Repository settings
  180. Repository = struct {
  181. AnsiCharset string
  182. ForcePrivate bool
  183. DefaultPrivate string
  184. MaxCreationLimit int
  185. MirrorQueueLength int
  186. PullRequestQueueLength int
  187. PreferredLicenses []string
  188. DisableHTTPGit bool
  189. UseCompatSSHURI bool
  190. // Repository editor settings
  191. Editor struct {
  192. LineWrapExtensions []string
  193. PreviewableFileModes []string
  194. } `ini:"-"`
  195. // Repository upload settings
  196. Upload struct {
  197. Enabled bool
  198. TempPath string
  199. AllowedTypes []string `delim:"|"`
  200. FileMaxSize int64
  201. MaxFiles int
  202. } `ini:"-"`
  203. // Repository local settings
  204. Local struct {
  205. LocalCopyPath string
  206. LocalWikiPath string
  207. } `ini:"-"`
  208. // Pull request settings
  209. PullRequest struct {
  210. WorkInProgressPrefixes []string
  211. } `ini:"repository.pull-request"`
  212. }{
  213. AnsiCharset: "",
  214. ForcePrivate: false,
  215. DefaultPrivate: RepoCreatingLastUserVisibility,
  216. MaxCreationLimit: -1,
  217. MirrorQueueLength: 1000,
  218. PullRequestQueueLength: 1000,
  219. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  220. DisableHTTPGit: false,
  221. UseCompatSSHURI: false,
  222. // Repository editor settings
  223. Editor: struct {
  224. LineWrapExtensions []string
  225. PreviewableFileModes []string
  226. }{
  227. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  228. PreviewableFileModes: []string{"markdown"},
  229. },
  230. // Repository upload settings
  231. Upload: struct {
  232. Enabled bool
  233. TempPath string
  234. AllowedTypes []string `delim:"|"`
  235. FileMaxSize int64
  236. MaxFiles int
  237. }{
  238. Enabled: true,
  239. TempPath: "data/tmp/uploads",
  240. AllowedTypes: []string{},
  241. FileMaxSize: 3,
  242. MaxFiles: 5,
  243. },
  244. // Repository local settings
  245. Local: struct {
  246. LocalCopyPath string
  247. LocalWikiPath string
  248. }{
  249. LocalCopyPath: "tmp/local-repo",
  250. LocalWikiPath: "tmp/local-wiki",
  251. },
  252. // Pull request settings
  253. PullRequest: struct {
  254. WorkInProgressPrefixes []string
  255. }{
  256. WorkInProgressPrefixes: defaultPullRequestWorkInProgressPrefixes,
  257. },
  258. }
  259. RepoRootPath string
  260. ScriptType = "bash"
  261. // UI settings
  262. UI = struct {
  263. ExplorePagingNum int
  264. IssuePagingNum int
  265. RepoSearchPagingNum int
  266. FeedMaxCommitNum int
  267. GraphMaxCommitNum int
  268. CodeCommentLines int
  269. ReactionMaxUserNum int
  270. ThemeColorMetaTag string
  271. MaxDisplayFileSize int64
  272. ShowUserEmail bool
  273. DefaultTheme string
  274. Admin struct {
  275. UserPagingNum int
  276. RepoPagingNum int
  277. NoticePagingNum int
  278. OrgPagingNum int
  279. } `ini:"ui.admin"`
  280. User struct {
  281. RepoPagingNum int
  282. } `ini:"ui.user"`
  283. Meta struct {
  284. Author string
  285. Description string
  286. Keywords string
  287. } `ini:"ui.meta"`
  288. }{
  289. ExplorePagingNum: 20,
  290. IssuePagingNum: 10,
  291. RepoSearchPagingNum: 10,
  292. FeedMaxCommitNum: 5,
  293. GraphMaxCommitNum: 100,
  294. CodeCommentLines: 4,
  295. ReactionMaxUserNum: 10,
  296. ThemeColorMetaTag: `#6cc644`,
  297. MaxDisplayFileSize: 8388608,
  298. DefaultTheme: `gitea`,
  299. Admin: struct {
  300. UserPagingNum int
  301. RepoPagingNum int
  302. NoticePagingNum int
  303. OrgPagingNum int
  304. }{
  305. UserPagingNum: 50,
  306. RepoPagingNum: 50,
  307. NoticePagingNum: 25,
  308. OrgPagingNum: 50,
  309. },
  310. User: struct {
  311. RepoPagingNum int
  312. }{
  313. RepoPagingNum: 15,
  314. },
  315. Meta: struct {
  316. Author string
  317. Description string
  318. Keywords string
  319. }{
  320. Author: "Gitea - Git with a cup of tea",
  321. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  322. Keywords: "go,git,self-hosted,gitea",
  323. },
  324. }
  325. // Markdown settings
  326. Markdown = struct {
  327. EnableHardLineBreak bool
  328. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  329. FileExtensions []string
  330. }{
  331. EnableHardLineBreak: false,
  332. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  333. }
  334. // Admin settings
  335. Admin struct {
  336. DisableRegularOrgCreation bool
  337. }
  338. // Picture settings
  339. AvatarUploadPath string
  340. AvatarMaxWidth int
  341. AvatarMaxHeight int
  342. GravatarSource string
  343. GravatarSourceURL *url.URL
  344. DisableGravatar bool
  345. EnableFederatedAvatar bool
  346. LibravatarService *libravatar.Libravatar
  347. // Log settings
  348. LogLevel string
  349. LogRootPath string
  350. LogModes []string
  351. LogConfigs []string
  352. // Attachment settings
  353. AttachmentPath string
  354. AttachmentAllowedTypes string
  355. AttachmentMaxSize int64
  356. AttachmentMaxFiles int
  357. AttachmentEnabled bool
  358. // Time settings
  359. TimeFormat string
  360. // Session settings
  361. SessionConfig session.Options
  362. CSRFCookieName = "_csrf"
  363. // Cron tasks
  364. Cron = struct {
  365. UpdateMirror struct {
  366. Enabled bool
  367. RunAtStart bool
  368. Schedule string
  369. } `ini:"cron.update_mirrors"`
  370. RepoHealthCheck struct {
  371. Enabled bool
  372. RunAtStart bool
  373. Schedule string
  374. Timeout time.Duration
  375. Args []string `delim:" "`
  376. } `ini:"cron.repo_health_check"`
  377. CheckRepoStats struct {
  378. Enabled bool
  379. RunAtStart bool
  380. Schedule string
  381. } `ini:"cron.check_repo_stats"`
  382. ArchiveCleanup struct {
  383. Enabled bool
  384. RunAtStart bool
  385. Schedule string
  386. OlderThan time.Duration
  387. } `ini:"cron.archive_cleanup"`
  388. SyncExternalUsers struct {
  389. Enabled bool
  390. RunAtStart bool
  391. Schedule string
  392. UpdateExisting bool
  393. } `ini:"cron.sync_external_users"`
  394. DeletedBranchesCleanup struct {
  395. Enabled bool
  396. RunAtStart bool
  397. Schedule string
  398. OlderThan time.Duration
  399. } `ini:"cron.deleted_branches_cleanup"`
  400. }{
  401. UpdateMirror: struct {
  402. Enabled bool
  403. RunAtStart bool
  404. Schedule string
  405. }{
  406. Enabled: true,
  407. RunAtStart: false,
  408. Schedule: "@every 10m",
  409. },
  410. RepoHealthCheck: struct {
  411. Enabled bool
  412. RunAtStart bool
  413. Schedule string
  414. Timeout time.Duration
  415. Args []string `delim:" "`
  416. }{
  417. Enabled: true,
  418. RunAtStart: false,
  419. Schedule: "@every 24h",
  420. Timeout: 60 * time.Second,
  421. Args: []string{},
  422. },
  423. CheckRepoStats: struct {
  424. Enabled bool
  425. RunAtStart bool
  426. Schedule string
  427. }{
  428. Enabled: true,
  429. RunAtStart: true,
  430. Schedule: "@every 24h",
  431. },
  432. ArchiveCleanup: struct {
  433. Enabled bool
  434. RunAtStart bool
  435. Schedule string
  436. OlderThan time.Duration
  437. }{
  438. Enabled: true,
  439. RunAtStart: true,
  440. Schedule: "@every 24h",
  441. OlderThan: 24 * time.Hour,
  442. },
  443. SyncExternalUsers: struct {
  444. Enabled bool
  445. RunAtStart bool
  446. Schedule string
  447. UpdateExisting bool
  448. }{
  449. Enabled: true,
  450. RunAtStart: false,
  451. Schedule: "@every 24h",
  452. UpdateExisting: true,
  453. },
  454. DeletedBranchesCleanup: struct {
  455. Enabled bool
  456. RunAtStart bool
  457. Schedule string
  458. OlderThan time.Duration
  459. }{
  460. Enabled: true,
  461. RunAtStart: true,
  462. Schedule: "@every 24h",
  463. OlderThan: 24 * time.Hour,
  464. },
  465. }
  466. // Git settings
  467. Git = struct {
  468. Version string `ini:"-"`
  469. DisableDiffHighlight bool
  470. MaxGitDiffLines int
  471. MaxGitDiffLineCharacters int
  472. MaxGitDiffFiles int
  473. GCArgs []string `delim:" "`
  474. Timeout struct {
  475. Migrate int
  476. Mirror int
  477. Clone int
  478. Pull int
  479. GC int `ini:"GC"`
  480. } `ini:"git.timeout"`
  481. }{
  482. DisableDiffHighlight: false,
  483. MaxGitDiffLines: 1000,
  484. MaxGitDiffLineCharacters: 5000,
  485. MaxGitDiffFiles: 100,
  486. GCArgs: []string{},
  487. Timeout: struct {
  488. Migrate int
  489. Mirror int
  490. Clone int
  491. Pull int
  492. GC int `ini:"GC"`
  493. }{
  494. Migrate: 600,
  495. Mirror: 300,
  496. Clone: 300,
  497. Pull: 300,
  498. GC: 60,
  499. },
  500. }
  501. // Mirror settings
  502. Mirror struct {
  503. DefaultInterval time.Duration
  504. MinInterval time.Duration
  505. }
  506. // API settings
  507. API = struct {
  508. EnableSwagger bool
  509. MaxResponseItems int
  510. }{
  511. EnableSwagger: true,
  512. MaxResponseItems: 50,
  513. }
  514. U2F = struct {
  515. AppID string
  516. TrustedFacets []string
  517. }{}
  518. // I18n settings
  519. Langs []string
  520. Names []string
  521. dateLangs map[string]string
  522. // Highlight settings are loaded in modules/template/highlight.go
  523. // Other settings
  524. ShowFooterBranding bool
  525. ShowFooterVersion bool
  526. ShowFooterTemplateLoadTime bool
  527. // Global setting objects
  528. Cfg *ini.File
  529. CustomPath string // Custom directory path
  530. CustomConf string
  531. CustomPID string
  532. ProdMode bool
  533. RunUser string
  534. IsWindows bool
  535. HasRobotsTxt bool
  536. InternalToken string // internal access token
  537. IterateBufferSize int
  538. ExternalMarkupParsers []MarkupParser
  539. // UILocation is the location on the UI, so that we can display the time on UI.
  540. // Currently only show the default time.Local, it could be added to app.ini after UI is ready
  541. UILocation = time.Local
  542. )
  543. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  544. func DateLang(lang string) string {
  545. name, ok := dateLangs[lang]
  546. if ok {
  547. return name
  548. }
  549. return "en"
  550. }
  551. func getAppPath() (string, error) {
  552. var appPath string
  553. var err error
  554. if IsWindows && filepath.IsAbs(os.Args[0]) {
  555. appPath = filepath.Clean(os.Args[0])
  556. } else {
  557. appPath, err = exec.LookPath(os.Args[0])
  558. }
  559. if err != nil {
  560. return "", err
  561. }
  562. appPath, err = filepath.Abs(appPath)
  563. if err != nil {
  564. return "", err
  565. }
  566. // Note: we don't use path.Dir here because it does not handle case
  567. // which path starts with two "/" in Windows: "//psf/Home/..."
  568. return strings.Replace(appPath, "\\", "/", -1), err
  569. }
  570. func getWorkPath(appPath string) string {
  571. workPath := ""
  572. giteaWorkPath := os.Getenv("GITEA_WORK_DIR")
  573. if len(giteaWorkPath) > 0 {
  574. workPath = giteaWorkPath
  575. } else {
  576. i := strings.LastIndex(appPath, "/")
  577. if i == -1 {
  578. workPath = appPath
  579. } else {
  580. workPath = appPath[:i]
  581. }
  582. }
  583. return strings.Replace(workPath, "\\", "/", -1)
  584. }
  585. func init() {
  586. IsWindows = runtime.GOOS == "windows"
  587. log.NewLogger(0, "console", `{"level": 0}`)
  588. var err error
  589. if AppPath, err = getAppPath(); err != nil {
  590. log.Fatal(4, "Failed to get app path: %v", err)
  591. }
  592. AppWorkPath = getWorkPath(AppPath)
  593. }
  594. func forcePathSeparator(path string) {
  595. if strings.Contains(path, "\\") {
  596. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  597. }
  598. }
  599. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  600. // actual user that runs the app. The first return value is the actual user name.
  601. // This check is ignored under Windows since SSH remote login is not the main
  602. // method to login on Windows.
  603. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  604. if IsWindows {
  605. return "", true
  606. }
  607. currentUser := user.CurrentUsername()
  608. return currentUser, runUser == currentUser
  609. }
  610. func createPIDFile(pidPath string) {
  611. currentPid := os.Getpid()
  612. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  613. log.Fatal(4, "Failed to create PID folder: %v", err)
  614. }
  615. file, err := os.Create(pidPath)
  616. if err != nil {
  617. log.Fatal(4, "Failed to create PID file: %v", err)
  618. }
  619. defer file.Close()
  620. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  621. log.Fatal(4, "Failed to write PID information: %v", err)
  622. }
  623. }
  624. // NewContext initializes configuration context.
  625. // NOTE: do not print any log except error.
  626. func NewContext() {
  627. Cfg = ini.Empty()
  628. CustomPath = os.Getenv("GITEA_CUSTOM")
  629. if len(CustomPath) == 0 {
  630. CustomPath = path.Join(AppWorkPath, "custom")
  631. } else if !filepath.IsAbs(CustomPath) {
  632. CustomPath = path.Join(AppWorkPath, CustomPath)
  633. }
  634. if len(CustomPID) > 0 {
  635. createPIDFile(CustomPID)
  636. }
  637. if len(CustomConf) == 0 {
  638. CustomConf = path.Join(CustomPath, "conf/app.ini")
  639. } else if !filepath.IsAbs(CustomConf) {
  640. CustomConf = path.Join(CustomPath, CustomConf)
  641. }
  642. if com.IsFile(CustomConf) {
  643. if err := Cfg.Append(CustomConf); err != nil {
  644. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  645. }
  646. } else {
  647. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  648. }
  649. Cfg.NameMapper = ini.AllCapsUnderscore
  650. homeDir, err := com.HomeDir()
  651. if err != nil {
  652. log.Fatal(4, "Failed to get home directory: %v", err)
  653. }
  654. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  655. LogLevel = getLogLevel("log", "LEVEL", "Info")
  656. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  657. forcePathSeparator(LogRootPath)
  658. sec := Cfg.Section("server")
  659. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  660. Protocol = HTTP
  661. if sec.Key("PROTOCOL").String() == "https" {
  662. Protocol = HTTPS
  663. CertFile = sec.Key("CERT_FILE").String()
  664. KeyFile = sec.Key("KEY_FILE").String()
  665. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  666. Protocol = FCGI
  667. } else if sec.Key("PROTOCOL").String() == "unix" {
  668. Protocol = UnixSocket
  669. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  670. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  671. if err != nil || UnixSocketPermissionParsed > 0777 {
  672. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  673. }
  674. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  675. }
  676. EnableLetsEncrypt := sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  677. LetsEncryptTOS := sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  678. if !LetsEncryptTOS && EnableLetsEncrypt {
  679. log.Warn("Failed to enable Let's Encrypt due to Let's Encrypt TOS not being accepted")
  680. EnableLetsEncrypt = false
  681. }
  682. LetsEncryptDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  683. LetsEncryptEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  684. Domain = sec.Key("DOMAIN").MustString("localhost")
  685. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  686. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  687. defaultAppURL := string(Protocol) + "://" + Domain
  688. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  689. defaultAppURL += ":" + HTTPPort
  690. }
  691. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL)
  692. AppURL = strings.TrimRight(AppURL, "/") + "/"
  693. // Check if has app suburl.
  694. url, err := url.Parse(AppURL)
  695. if err != nil {
  696. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  697. }
  698. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  699. // This value is empty if site does not have sub-url.
  700. AppSubURL = strings.TrimSuffix(url.Path, "/")
  701. AppSubURLDepth = strings.Count(AppSubURL, "/")
  702. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  703. // TODO: Can be replaced with url.Hostname() when minimal GoLang version is 1.8
  704. urlHostname := strings.SplitN(url.Host, ":", 2)[0]
  705. if urlHostname != Domain && net.ParseIP(urlHostname) == nil {
  706. Domain = urlHostname
  707. }
  708. var defaultLocalURL string
  709. switch Protocol {
  710. case UnixSocket:
  711. defaultLocalURL = "http://unix/"
  712. case FCGI:
  713. defaultLocalURL = AppURL
  714. default:
  715. defaultLocalURL = string(Protocol) + "://"
  716. if HTTPAddr == "0.0.0.0" {
  717. defaultLocalURL += "localhost"
  718. } else {
  719. defaultLocalURL += HTTPAddr
  720. }
  721. defaultLocalURL += ":" + HTTPPort + "/"
  722. }
  723. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  724. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  725. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  726. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  727. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  728. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(AppWorkPath)
  729. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  730. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  731. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  732. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  733. if !filepath.IsAbs(PprofDataPath) {
  734. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  735. }
  736. switch sec.Key("LANDING_PAGE").MustString("home") {
  737. case "explore":
  738. LandingPageURL = LandingPageExplore
  739. case "organizations":
  740. LandingPageURL = LandingPageOrganizations
  741. default:
  742. LandingPageURL = LandingPageHome
  743. }
  744. if len(SSH.Domain) == 0 {
  745. SSH.Domain = Domain
  746. }
  747. SSH.RootPath = path.Join(homeDir, ".ssh")
  748. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  749. if len(serverCiphers) > 0 {
  750. SSH.ServerCiphers = serverCiphers
  751. }
  752. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  753. if len(serverKeyExchanges) > 0 {
  754. SSH.ServerKeyExchanges = serverKeyExchanges
  755. }
  756. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  757. if len(serverMACs) > 0 {
  758. SSH.ServerMACs = serverMACs
  759. }
  760. SSH.KeyTestPath = os.TempDir()
  761. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  762. log.Fatal(4, "Failed to map SSH settings: %v", err)
  763. }
  764. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  765. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  766. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  767. // When disable SSH, start builtin server value is ignored.
  768. if SSH.Disabled {
  769. SSH.StartBuiltinServer = false
  770. }
  771. if !SSH.Disabled && !SSH.StartBuiltinServer {
  772. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  773. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  774. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  775. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  776. }
  777. }
  778. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  779. SSH.MinimumKeySizes = map[string]int{}
  780. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  781. for _, key := range minimumKeySizes {
  782. if key.MustInt() != -1 {
  783. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  784. }
  785. }
  786. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  787. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  788. sec = Cfg.Section("server")
  789. if err = sec.MapTo(&LFS); err != nil {
  790. log.Fatal(4, "Failed to map LFS settings: %v", err)
  791. }
  792. LFS.ContentPath = sec.Key("LFS_CONTENT_PATH").MustString(filepath.Join(AppDataPath, "lfs"))
  793. if !filepath.IsAbs(LFS.ContentPath) {
  794. LFS.ContentPath = filepath.Join(AppWorkPath, LFS.ContentPath)
  795. }
  796. LFS.HTTPAuthExpiry = sec.Key("LFS_HTTP_AUTH_EXPIRY").MustDuration(20 * time.Minute)
  797. if LFS.StartServer {
  798. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  799. log.Fatal(4, "Failed to create '%s': %v", LFS.ContentPath, err)
  800. }
  801. LFS.JWTSecretBytes = make([]byte, 32)
  802. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  803. if err != nil || n != 32 {
  804. LFS.JWTSecretBase64, err = generate.NewLfsJwtSecret()
  805. if err != nil {
  806. log.Fatal(4, "Error generating JWT Secret for custom config: %v", err)
  807. return
  808. }
  809. // Save secret
  810. cfg := ini.Empty()
  811. if com.IsFile(CustomConf) {
  812. // Keeps custom settings if there is already something.
  813. if err := cfg.Append(CustomConf); err != nil {
  814. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  815. }
  816. }
  817. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  818. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  819. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  820. }
  821. if err := cfg.SaveTo(CustomConf); err != nil {
  822. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  823. return
  824. }
  825. }
  826. //Disable LFS client hooks if installed for the current OS user
  827. //Needs at least git v2.1.2
  828. binVersion, err := git.BinVersion()
  829. if err != nil {
  830. log.Fatal(4, "Error retrieving git version: %v", err)
  831. }
  832. splitVersion := strings.SplitN(binVersion, ".", 4)
  833. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  834. if err != nil {
  835. log.Fatal(4, "Error parsing git major version: %v", err)
  836. }
  837. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  838. if err != nil {
  839. log.Fatal(4, "Error parsing git minor version: %v", err)
  840. }
  841. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  842. if err != nil {
  843. log.Fatal(4, "Error parsing git revision version: %v", err)
  844. }
  845. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  846. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  847. LFS.StartServer = false
  848. log.Error(4, "LFS server support needs at least Git v2.1.2")
  849. } else {
  850. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  851. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  852. }
  853. }
  854. sec = Cfg.Section("security")
  855. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  856. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  857. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  858. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  859. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  860. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  861. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  862. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  863. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(false)
  864. InternalToken = sec.Key("INTERNAL_TOKEN").String()
  865. if len(InternalToken) == 0 {
  866. InternalToken, err = generate.NewInternalToken()
  867. if err != nil {
  868. log.Fatal(4, "Error generate internal token: %v", err)
  869. }
  870. // Save secret
  871. cfgSave := ini.Empty()
  872. if com.IsFile(CustomConf) {
  873. // Keeps custom settings if there is already something.
  874. if err := cfgSave.Append(CustomConf); err != nil {
  875. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  876. }
  877. }
  878. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(InternalToken)
  879. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  880. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  881. }
  882. if err := cfgSave.SaveTo(CustomConf); err != nil {
  883. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  884. }
  885. }
  886. IterateBufferSize = Cfg.Section("database").Key("ITERATE_BUFFER_SIZE").MustInt(50)
  887. LogSQL = Cfg.Section("database").Key("LOG_SQL").MustBool(true)
  888. sec = Cfg.Section("attachment")
  889. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  890. if !filepath.IsAbs(AttachmentPath) {
  891. AttachmentPath = path.Join(AppWorkPath, AttachmentPath)
  892. }
  893. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png,application/zip,application/gzip"), "|", ",", -1)
  894. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  895. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  896. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  897. TimeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("RFC1123")
  898. TimeFormat = map[string]string{
  899. "ANSIC": time.ANSIC,
  900. "UnixDate": time.UnixDate,
  901. "RubyDate": time.RubyDate,
  902. "RFC822": time.RFC822,
  903. "RFC822Z": time.RFC822Z,
  904. "RFC850": time.RFC850,
  905. "RFC1123": time.RFC1123,
  906. "RFC1123Z": time.RFC1123Z,
  907. "RFC3339": time.RFC3339,
  908. "RFC3339Nano": time.RFC3339Nano,
  909. "Kitchen": time.Kitchen,
  910. "Stamp": time.Stamp,
  911. "StampMilli": time.StampMilli,
  912. "StampMicro": time.StampMicro,
  913. "StampNano": time.StampNano,
  914. }[TimeFormatKey]
  915. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  916. if len(TimeFormat) == 0 {
  917. TimeFormat = TimeFormatKey
  918. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  919. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  920. log.Fatal(4, "Can't create time properly, please check your time format has 2006, 01, 02, 15, 04 and 05")
  921. }
  922. log.Trace("Custom TimeFormat: %s", TimeFormat)
  923. }
  924. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  925. // Does not check run user when the install lock is off.
  926. if InstallLock {
  927. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  928. if !match {
  929. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  930. }
  931. }
  932. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  933. // Determine and create root git repository path.
  934. sec = Cfg.Section("repository")
  935. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  936. Repository.UseCompatSSHURI = sec.Key("USE_COMPAT_SSH_URI").MustBool()
  937. Repository.MaxCreationLimit = sec.Key("MAX_CREATION_LIMIT").MustInt(-1)
  938. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  939. forcePathSeparator(RepoRootPath)
  940. if !filepath.IsAbs(RepoRootPath) {
  941. RepoRootPath = filepath.Join(AppWorkPath, RepoRootPath)
  942. } else {
  943. RepoRootPath = filepath.Clean(RepoRootPath)
  944. }
  945. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  946. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  947. log.Fatal(4, "Failed to map Repository settings: %v", err)
  948. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  949. log.Fatal(4, "Failed to map Repository.Editor settings: %v", err)
  950. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  951. log.Fatal(4, "Failed to map Repository.Upload settings: %v", err)
  952. } else if err = Cfg.Section("repository.local").MapTo(&Repository.Local); err != nil {
  953. log.Fatal(4, "Failed to map Repository.Local settings: %v", err)
  954. } else if err = Cfg.Section("repository.pull-request").MapTo(&Repository.PullRequest); err != nil {
  955. log.Fatal(4, "Failed to map Repository.PullRequest settings: %v", err)
  956. }
  957. if !filepath.IsAbs(Repository.Upload.TempPath) {
  958. Repository.Upload.TempPath = path.Join(AppWorkPath, Repository.Upload.TempPath)
  959. }
  960. sec = Cfg.Section("picture")
  961. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  962. forcePathSeparator(AvatarUploadPath)
  963. if !filepath.IsAbs(AvatarUploadPath) {
  964. AvatarUploadPath = path.Join(AppWorkPath, AvatarUploadPath)
  965. }
  966. AvatarMaxWidth = sec.Key("AVATAR_MAX_WIDTH").MustInt(4096)
  967. AvatarMaxHeight = sec.Key("AVATAR_MAX_HEIGHT").MustInt(3072)
  968. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  969. case "duoshuo":
  970. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  971. case "gravatar":
  972. GravatarSource = "https://secure.gravatar.com/avatar/"
  973. case "libravatar":
  974. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  975. default:
  976. GravatarSource = source
  977. }
  978. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  979. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(!InstallLock)
  980. if OfflineMode {
  981. DisableGravatar = true
  982. EnableFederatedAvatar = false
  983. }
  984. if DisableGravatar {
  985. EnableFederatedAvatar = false
  986. }
  987. if EnableFederatedAvatar || !DisableGravatar {
  988. GravatarSourceURL, err = url.Parse(GravatarSource)
  989. if err != nil {
  990. log.Fatal(4, "Failed to parse Gravatar URL(%s): %v",
  991. GravatarSource, err)
  992. }
  993. }
  994. if EnableFederatedAvatar {
  995. LibravatarService = libravatar.New()
  996. if GravatarSourceURL.Scheme == "https" {
  997. LibravatarService.SetUseHTTPS(true)
  998. LibravatarService.SetSecureFallbackHost(GravatarSourceURL.Host)
  999. } else {
  1000. LibravatarService.SetUseHTTPS(false)
  1001. LibravatarService.SetFallbackHost(GravatarSourceURL.Host)
  1002. }
  1003. }
  1004. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  1005. log.Fatal(4, "Failed to map UI settings: %v", err)
  1006. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  1007. log.Fatal(4, "Failed to map Markdown settings: %v", err)
  1008. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  1009. log.Fatal(4, "Fail to map Admin settings: %v", err)
  1010. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  1011. log.Fatal(4, "Failed to map Cron settings: %v", err)
  1012. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  1013. log.Fatal(4, "Failed to map Git settings: %v", err)
  1014. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  1015. log.Fatal(4, "Failed to map API settings: %v", err)
  1016. }
  1017. sec = Cfg.Section("mirror")
  1018. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  1019. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  1020. if Mirror.MinInterval.Minutes() < 1 {
  1021. log.Warn("Mirror.MinInterval is too low")
  1022. Mirror.MinInterval = 1 * time.Minute
  1023. }
  1024. if Mirror.DefaultInterval < Mirror.MinInterval {
  1025. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  1026. Mirror.DefaultInterval = time.Hour * 8
  1027. }
  1028. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  1029. if len(Langs) == 0 {
  1030. Langs = defaultLangs
  1031. }
  1032. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  1033. if len(Names) == 0 {
  1034. Names = defaultLangNames
  1035. }
  1036. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  1037. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  1038. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  1039. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  1040. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  1041. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  1042. extensionReg := regexp.MustCompile(`\.\w`)
  1043. for _, sec := range Cfg.Section("markup").ChildSections() {
  1044. name := strings.TrimLeft(sec.Name(), "markup.")
  1045. if name == "" {
  1046. log.Warn("name is empty, markup " + sec.Name() + "ignored")
  1047. continue
  1048. }
  1049. extensions := sec.Key("FILE_EXTENSIONS").Strings(",")
  1050. var exts = make([]string, 0, len(extensions))
  1051. for _, extension := range extensions {
  1052. if !extensionReg.MatchString(extension) {
  1053. log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored")
  1054. } else {
  1055. exts = append(exts, extension)
  1056. }
  1057. }
  1058. if len(exts) == 0 {
  1059. log.Warn(sec.Name() + " file extension is empty, markup " + name + " ignored")
  1060. continue
  1061. }
  1062. command := sec.Key("RENDER_COMMAND").MustString("")
  1063. if command == "" {
  1064. log.Warn(" RENDER_COMMAND is empty, markup " + name + " ignored")
  1065. continue
  1066. }
  1067. ExternalMarkupParsers = append(ExternalMarkupParsers, MarkupParser{
  1068. Enabled: sec.Key("ENABLED").MustBool(false),
  1069. MarkupName: name,
  1070. FileExtensions: exts,
  1071. Command: command,
  1072. IsInputFile: sec.Key("IS_INPUT_FILE").MustBool(false),
  1073. })
  1074. }
  1075. sec = Cfg.Section("U2F")
  1076. U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimRight(AppURL, "/")))
  1077. U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimRight(AppURL, "/"))
  1078. }
  1079. // Service settings
  1080. var Service struct {
  1081. ActiveCodeLives int
  1082. ResetPwdCodeLives int
  1083. RegisterEmailConfirm bool
  1084. DisableRegistration bool
  1085. AllowOnlyExternalRegistration bool
  1086. ShowRegistrationButton bool
  1087. RequireSignInView bool
  1088. EnableNotifyMail bool
  1089. EnableReverseProxyAuth bool
  1090. EnableReverseProxyAutoRegister bool
  1091. EnableCaptcha bool
  1092. CaptchaType string
  1093. RecaptchaSecret string
  1094. RecaptchaSitekey string
  1095. DefaultKeepEmailPrivate bool
  1096. DefaultAllowCreateOrganization bool
  1097. EnableTimetracking bool
  1098. DefaultEnableTimetracking bool
  1099. DefaultEnableDependencies bool
  1100. DefaultAllowOnlyContributorsToTrackTime bool
  1101. NoReplyAddress string
  1102. // OpenID settings
  1103. EnableOpenIDSignIn bool
  1104. EnableOpenIDSignUp bool
  1105. OpenIDWhitelist []*regexp.Regexp
  1106. OpenIDBlacklist []*regexp.Regexp
  1107. }
  1108. func newService() {
  1109. sec := Cfg.Section("service")
  1110. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  1111. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  1112. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  1113. Service.AllowOnlyExternalRegistration = sec.Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").MustBool()
  1114. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!(Service.DisableRegistration || Service.AllowOnlyExternalRegistration))
  1115. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  1116. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  1117. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  1118. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool(false)
  1119. Service.CaptchaType = sec.Key("CAPTCHA_TYPE").MustString(ImageCaptcha)
  1120. Service.RecaptchaSecret = sec.Key("RECAPTCHA_SECRET").MustString("")
  1121. Service.RecaptchaSitekey = sec.Key("RECAPTCHA_SITEKEY").MustString("")
  1122. Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
  1123. Service.DefaultAllowCreateOrganization = sec.Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").MustBool(true)
  1124. Service.EnableTimetracking = sec.Key("ENABLE_TIMETRACKING").MustBool(true)
  1125. if Service.EnableTimetracking {
  1126. Service.DefaultEnableTimetracking = sec.Key("DEFAULT_ENABLE_TIMETRACKING").MustBool(true)
  1127. }
  1128. Service.DefaultEnableDependencies = sec.Key("DEFAULT_ENABLE_DEPENDENCIES").MustBool(true)
  1129. Service.DefaultAllowOnlyContributorsToTrackTime = sec.Key("DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME").MustBool(true)
  1130. Service.NoReplyAddress = sec.Key("NO_REPLY_ADDRESS").MustString("noreply.example.org")
  1131. sec = Cfg.Section("openid")
  1132. Service.EnableOpenIDSignIn = sec.Key("ENABLE_OPENID_SIGNIN").MustBool(!InstallLock)
  1133. Service.EnableOpenIDSignUp = sec.Key("ENABLE_OPENID_SIGNUP").MustBool(!Service.DisableRegistration && Service.EnableOpenIDSignIn)
  1134. pats := sec.Key("WHITELISTED_URIS").Strings(" ")
  1135. if len(pats) != 0 {
  1136. Service.OpenIDWhitelist = make([]*regexp.Regexp, len(pats))
  1137. for i, p := range pats {
  1138. Service.OpenIDWhitelist[i] = regexp.MustCompilePOSIX(p)
  1139. }
  1140. }
  1141. pats = sec.Key("BLACKLISTED_URIS").Strings(" ")
  1142. if len(pats) != 0 {
  1143. Service.OpenIDBlacklist = make([]*regexp.Regexp, len(pats))
  1144. for i, p := range pats {
  1145. Service.OpenIDBlacklist[i] = regexp.MustCompilePOSIX(p)
  1146. }
  1147. }
  1148. }
  1149. var logLevels = map[string]string{
  1150. "Trace": "0",
  1151. "Debug": "1",
  1152. "Info": "2",
  1153. "Warn": "3",
  1154. "Error": "4",
  1155. "Critical": "5",
  1156. }
  1157. func getLogLevel(section string, key string, defaultValue string) string {
  1158. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  1159. return Cfg.Section(section).Key(key).In(defaultValue, validLevels)
  1160. }
  1161. func newLogService() {
  1162. log.Info("Gitea v%s%s", AppVer, AppBuiltWith)
  1163. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1164. LogConfigs = make([]string, len(LogModes))
  1165. useConsole := false
  1166. for i := 0; i < len(LogModes); i++ {
  1167. LogModes[i] = strings.TrimSpace(LogModes[i])
  1168. if LogModes[i] == "console" {
  1169. useConsole = true
  1170. }
  1171. }
  1172. if !useConsole {
  1173. log.DelLogger("console")
  1174. }
  1175. for i, mode := range LogModes {
  1176. sec, err := Cfg.GetSection("log." + mode)
  1177. if err != nil {
  1178. sec, _ = Cfg.NewSection("log." + mode)
  1179. }
  1180. // Log level.
  1181. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1182. level, ok := logLevels[levelName]
  1183. if !ok {
  1184. log.Fatal(4, "Unknown log level: %s", levelName)
  1185. }
  1186. // Generate log configuration.
  1187. switch mode {
  1188. case "console":
  1189. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  1190. case "file":
  1191. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gitea.log"))
  1192. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1193. panic(err.Error())
  1194. }
  1195. LogConfigs[i] = fmt.Sprintf(
  1196. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1197. logPath,
  1198. sec.Key("LOG_ROTATE").MustBool(true),
  1199. sec.Key("MAX_LINES").MustInt(1000000),
  1200. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1201. sec.Key("DAILY_ROTATE").MustBool(true),
  1202. sec.Key("MAX_DAYS").MustInt(7))
  1203. case "conn":
  1204. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1205. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1206. sec.Key("RECONNECT").MustBool(),
  1207. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1208. sec.Key("ADDR").MustString(":7020"))
  1209. case "smtp":
  1210. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  1211. sec.Key("USER").MustString("example@example.com"),
  1212. sec.Key("PASSWD").MustString("******"),
  1213. sec.Key("HOST").MustString("127.0.0.1:25"),
  1214. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  1215. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1216. case "database":
  1217. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1218. sec.Key("DRIVER").String(),
  1219. sec.Key("CONN").String())
  1220. }
  1221. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  1222. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  1223. }
  1224. }
  1225. // NewXORMLogService initializes xorm logger service
  1226. func NewXORMLogService(disableConsole bool) {
  1227. logModes := strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1228. var logConfigs string
  1229. for _, mode := range logModes {
  1230. mode = strings.TrimSpace(mode)
  1231. if disableConsole && mode == "console" {
  1232. continue
  1233. }
  1234. sec, err := Cfg.GetSection("log." + mode)
  1235. if err != nil {
  1236. sec, _ = Cfg.NewSection("log." + mode)
  1237. }
  1238. // Log level.
  1239. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1240. level, ok := logLevels[levelName]
  1241. if !ok {
  1242. log.Fatal(4, "Unknown log level: %s", levelName)
  1243. }
  1244. // Generate log configuration.
  1245. switch mode {
  1246. case "console":
  1247. logConfigs = fmt.Sprintf(`{"level":%s}`, level)
  1248. case "file":
  1249. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "xorm.log"))
  1250. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1251. panic(err.Error())
  1252. }
  1253. logPath = path.Join(filepath.Dir(logPath), "xorm.log")
  1254. logConfigs = fmt.Sprintf(
  1255. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1256. logPath,
  1257. sec.Key("LOG_ROTATE").MustBool(true),
  1258. sec.Key("MAX_LINES").MustInt(1000000),
  1259. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1260. sec.Key("DAILY_ROTATE").MustBool(true),
  1261. sec.Key("MAX_DAYS").MustInt(7))
  1262. case "conn":
  1263. logConfigs = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1264. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1265. sec.Key("RECONNECT").MustBool(),
  1266. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1267. sec.Key("ADDR").MustString(":7020"))
  1268. case "smtp":
  1269. logConfigs = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  1270. sec.Key("USER").MustString("example@example.com"),
  1271. sec.Key("PASSWD").MustString("******"),
  1272. sec.Key("HOST").MustString("127.0.0.1:25"),
  1273. sec.Key("RECEIVERS").MustString("[]"),
  1274. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1275. case "database":
  1276. logConfigs = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1277. sec.Key("DRIVER").String(),
  1278. sec.Key("CONN").String())
  1279. }
  1280. log.NewXORMLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, logConfigs)
  1281. if !disableConsole {
  1282. log.Info("XORM Log Mode: %s(%s)", strings.Title(mode), levelName)
  1283. }
  1284. var lvl core.LogLevel
  1285. switch levelName {
  1286. case "Trace", "Debug":
  1287. lvl = core.LOG_DEBUG
  1288. case "Info":
  1289. lvl = core.LOG_INFO
  1290. case "Warn":
  1291. lvl = core.LOG_WARNING
  1292. case "Error", "Critical":
  1293. lvl = core.LOG_ERR
  1294. }
  1295. log.XORMLogger.SetLevel(lvl)
  1296. }
  1297. if len(logConfigs) == 0 {
  1298. log.DiscardXORMLogger()
  1299. }
  1300. }
  1301. // Cache represents cache settings
  1302. type Cache struct {
  1303. Adapter string
  1304. Interval int
  1305. Conn string
  1306. TTL time.Duration
  1307. }
  1308. var (
  1309. // CacheService the global cache
  1310. CacheService *Cache
  1311. )
  1312. func newCacheService() {
  1313. sec := Cfg.Section("cache")
  1314. CacheService = &Cache{
  1315. Adapter: sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"}),
  1316. }
  1317. switch CacheService.Adapter {
  1318. case "memory":
  1319. CacheService.Interval = sec.Key("INTERVAL").MustInt(60)
  1320. case "redis", "memcache":
  1321. CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ")
  1322. default:
  1323. log.Fatal(4, "Unknown cache adapter: %s", CacheService.Adapter)
  1324. }
  1325. CacheService.TTL = sec.Key("ITEM_TTL").MustDuration(16 * time.Hour)
  1326. log.Info("Cache Service Enabled")
  1327. }
  1328. func newSessionService() {
  1329. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  1330. []string{"memory", "file", "redis", "mysql"})
  1331. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").MustString(path.Join(AppDataPath, "sessions")), "\" ")
  1332. if SessionConfig.Provider == "file" && !filepath.IsAbs(SessionConfig.ProviderConfig) {
  1333. SessionConfig.ProviderConfig = path.Join(AppWorkPath, SessionConfig.ProviderConfig)
  1334. }
  1335. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  1336. SessionConfig.CookiePath = AppSubURL
  1337. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  1338. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  1339. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  1340. log.Info("Session Service Enabled")
  1341. }
  1342. // Mailer represents mail service.
  1343. type Mailer struct {
  1344. // Mailer
  1345. QueueLength int
  1346. Name string
  1347. From string
  1348. FromName string
  1349. FromEmail string
  1350. SendAsPlainText bool
  1351. // SMTP sender
  1352. Host string
  1353. User, Passwd string
  1354. DisableHelo bool
  1355. HeloHostname string
  1356. SkipVerify bool
  1357. UseCertificate bool
  1358. CertFile, KeyFile string
  1359. // Sendmail sender
  1360. UseSendmail bool
  1361. SendmailPath string
  1362. SendmailArgs []string
  1363. }
  1364. var (
  1365. // MailService the global mailer
  1366. MailService *Mailer
  1367. )
  1368. func newMailService() {
  1369. sec := Cfg.Section("mailer")
  1370. // Check mailer setting.
  1371. if !sec.Key("ENABLED").MustBool() {
  1372. return
  1373. }
  1374. MailService = &Mailer{
  1375. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  1376. Name: sec.Key("NAME").MustString(AppName),
  1377. SendAsPlainText: sec.Key("SEND_AS_PLAIN_TEXT").MustBool(false),
  1378. Host: sec.Key("HOST").String(),
  1379. User: sec.Key("USER").String(),
  1380. Passwd: sec.Key("PASSWD").String(),
  1381. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  1382. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  1383. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  1384. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  1385. CertFile: sec.Key("CERT_FILE").String(),
  1386. KeyFile: sec.Key("KEY_FILE").String(),
  1387. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  1388. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  1389. }
  1390. MailService.From = sec.Key("FROM").MustString(MailService.User)
  1391. if sec.HasKey("ENABLE_HTML_ALTERNATIVE") {
  1392. log.Warn("ENABLE_HTML_ALTERNATIVE is deprecated, use SEND_AS_PLAIN_TEXT")
  1393. MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false)
  1394. }
  1395. parsed, err := mail.ParseAddress(MailService.From)
  1396. if err != nil {
  1397. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1398. }
  1399. MailService.FromName = parsed.Name
  1400. MailService.FromEmail = parsed.Address
  1401. if MailService.UseSendmail {
  1402. MailService.SendmailArgs, err = shellquote.Split(sec.Key("SENDMAIL_ARGS").String())
  1403. if err != nil {
  1404. log.Error(4, "Failed to parse Sendmail args: %v", CustomConf, err)
  1405. }
  1406. }
  1407. log.Info("Mail Service Enabled")
  1408. }
  1409. func newRegisterMailService() {
  1410. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1411. return
  1412. } else if MailService == nil {
  1413. log.Warn("Register Mail Service: Mail Service is not enabled")
  1414. return
  1415. }
  1416. Service.RegisterEmailConfirm = true
  1417. log.Info("Register Mail Service Enabled")
  1418. }
  1419. func newNotifyMailService() {
  1420. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1421. return
  1422. } else if MailService == nil {
  1423. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1424. return
  1425. }
  1426. Service.EnableNotifyMail = true
  1427. log.Info("Notify Mail Service Enabled")
  1428. }
  1429. func newWebhookService() {
  1430. sec := Cfg.Section("webhook")
  1431. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1432. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1433. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1434. Webhook.Types = []string{"gitea", "gogs", "slack", "discord", "dingtalk"}
  1435. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1436. }
  1437. // NewServices initializes the services
  1438. func NewServices() {
  1439. newService()
  1440. newLogService()
  1441. NewXORMLogService(false)
  1442. newCacheService()
  1443. newSessionService()
  1444. newMailService()
  1445. newRegisterMailService()
  1446. newNotifyMailService()
  1447. newWebhookService()
  1448. }