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

setting.go 46KB

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