You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 50KB

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