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

setting.go 46KB

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