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

setting.go 44KB

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