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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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. // I18n settings
  522. Langs []string
  523. Names []string
  524. dateLangs map[string]string
  525. // Highlight settings are loaded in modules/template/highlight.go
  526. // Other settings
  527. ShowFooterBranding bool
  528. ShowFooterVersion bool
  529. ShowFooterTemplateLoadTime bool
  530. // Global setting objects
  531. Cfg *ini.File
  532. CustomPath string // Custom directory path
  533. CustomConf string
  534. CustomPID string
  535. ProdMode bool
  536. RunUser string
  537. IsWindows bool
  538. HasRobotsTxt bool
  539. InternalToken string // internal access token
  540. IterateBufferSize int
  541. ExternalMarkupParsers []MarkupParser
  542. // UILocation is the location on the UI, so that we can display the time on UI.
  543. // Currently only show the default time.Local, it could be added to app.ini after UI is ready
  544. UILocation = time.Local
  545. )
  546. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  547. func DateLang(lang string) string {
  548. name, ok := dateLangs[lang]
  549. if ok {
  550. return name
  551. }
  552. return "en"
  553. }
  554. func getAppPath() (string, error) {
  555. var appPath string
  556. var err error
  557. if IsWindows && filepath.IsAbs(os.Args[0]) {
  558. appPath = filepath.Clean(os.Args[0])
  559. } else {
  560. appPath, err = exec.LookPath(os.Args[0])
  561. }
  562. if err != nil {
  563. return "", err
  564. }
  565. appPath, err = filepath.Abs(appPath)
  566. if err != nil {
  567. return "", err
  568. }
  569. // Note: we don't use path.Dir here because it does not handle case
  570. // which path starts with two "/" in Windows: "//psf/Home/..."
  571. return strings.Replace(appPath, "\\", "/", -1), err
  572. }
  573. func getWorkPath(appPath string) string {
  574. workPath := ""
  575. giteaWorkPath := os.Getenv("GITEA_WORK_DIR")
  576. if len(giteaWorkPath) > 0 {
  577. workPath = giteaWorkPath
  578. } else {
  579. i := strings.LastIndex(appPath, "/")
  580. if i == -1 {
  581. workPath = appPath
  582. } else {
  583. workPath = appPath[:i]
  584. }
  585. }
  586. return strings.Replace(workPath, "\\", "/", -1)
  587. }
  588. func init() {
  589. IsWindows = runtime.GOOS == "windows"
  590. log.NewLogger(0, "console", `{"level": 0}`)
  591. var err error
  592. if AppPath, err = getAppPath(); err != nil {
  593. log.Fatal(4, "Failed to get app path: %v", err)
  594. }
  595. AppWorkPath = getWorkPath(AppPath)
  596. }
  597. func forcePathSeparator(path string) {
  598. if strings.Contains(path, "\\") {
  599. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  600. }
  601. }
  602. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  603. // actual user that runs the app. The first return value is the actual user name.
  604. // This check is ignored under Windows since SSH remote login is not the main
  605. // method to login on Windows.
  606. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  607. if IsWindows {
  608. return "", true
  609. }
  610. currentUser := user.CurrentUsername()
  611. return currentUser, runUser == currentUser
  612. }
  613. func createPIDFile(pidPath string) {
  614. currentPid := os.Getpid()
  615. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  616. log.Fatal(4, "Failed to create PID folder: %v", err)
  617. }
  618. file, err := os.Create(pidPath)
  619. if err != nil {
  620. log.Fatal(4, "Failed to create PID file: %v", err)
  621. }
  622. defer file.Close()
  623. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  624. log.Fatal(4, "Failed to write PID information: %v", err)
  625. }
  626. }
  627. // NewContext initializes configuration context.
  628. // NOTE: do not print any log except error.
  629. func NewContext() {
  630. Cfg = ini.Empty()
  631. CustomPath = os.Getenv("GITEA_CUSTOM")
  632. if len(CustomPath) == 0 {
  633. CustomPath = path.Join(AppWorkPath, "custom")
  634. } else if !filepath.IsAbs(CustomPath) {
  635. CustomPath = path.Join(AppWorkPath, CustomPath)
  636. }
  637. if len(CustomPID) > 0 {
  638. createPIDFile(CustomPID)
  639. }
  640. if len(CustomConf) == 0 {
  641. CustomConf = path.Join(CustomPath, "conf/app.ini")
  642. } else if !filepath.IsAbs(CustomConf) {
  643. CustomConf = path.Join(CustomPath, CustomConf)
  644. }
  645. if com.IsFile(CustomConf) {
  646. if err := Cfg.Append(CustomConf); err != nil {
  647. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  648. }
  649. } else {
  650. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  651. }
  652. Cfg.NameMapper = ini.AllCapsUnderscore
  653. homeDir, err := com.HomeDir()
  654. if err != nil {
  655. log.Fatal(4, "Failed to get home directory: %v", err)
  656. }
  657. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  658. LogLevel = getLogLevel("log", "LEVEL", "Info")
  659. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  660. forcePathSeparator(LogRootPath)
  661. sec := Cfg.Section("server")
  662. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  663. Protocol = HTTP
  664. if sec.Key("PROTOCOL").String() == "https" {
  665. Protocol = HTTPS
  666. CertFile = sec.Key("CERT_FILE").String()
  667. KeyFile = sec.Key("KEY_FILE").String()
  668. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  669. Protocol = FCGI
  670. } else if sec.Key("PROTOCOL").String() == "unix" {
  671. Protocol = UnixSocket
  672. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  673. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  674. if err != nil || UnixSocketPermissionParsed > 0777 {
  675. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  676. }
  677. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  678. }
  679. EnableLetsEncrypt = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  680. LetsEncryptTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  681. if !LetsEncryptTOS && EnableLetsEncrypt {
  682. log.Warn("Failed to enable Let's Encrypt due to Let's Encrypt TOS not being accepted")
  683. EnableLetsEncrypt = false
  684. }
  685. LetsEncryptDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  686. LetsEncryptEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  687. Domain = sec.Key("DOMAIN").MustString("localhost")
  688. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  689. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  690. defaultAppURL := string(Protocol) + "://" + Domain
  691. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  692. defaultAppURL += ":" + HTTPPort
  693. }
  694. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL)
  695. AppURL = strings.TrimRight(AppURL, "/") + "/"
  696. // Check if has app suburl.
  697. url, err := url.Parse(AppURL)
  698. if err != nil {
  699. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  700. }
  701. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  702. // This value is empty if site does not have sub-url.
  703. AppSubURL = strings.TrimSuffix(url.Path, "/")
  704. AppSubURLDepth = strings.Count(AppSubURL, "/")
  705. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  706. // TODO: Can be replaced with url.Hostname() when minimal GoLang version is 1.8
  707. urlHostname := strings.SplitN(url.Host, ":", 2)[0]
  708. if urlHostname != Domain && net.ParseIP(urlHostname) == nil {
  709. Domain = urlHostname
  710. }
  711. var defaultLocalURL string
  712. switch Protocol {
  713. case UnixSocket:
  714. defaultLocalURL = "http://unix/"
  715. case FCGI:
  716. defaultLocalURL = AppURL
  717. default:
  718. defaultLocalURL = string(Protocol) + "://"
  719. if HTTPAddr == "0.0.0.0" {
  720. defaultLocalURL += "localhost"
  721. } else {
  722. defaultLocalURL += HTTPAddr
  723. }
  724. defaultLocalURL += ":" + HTTPPort + "/"
  725. }
  726. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  727. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  728. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  729. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  730. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  731. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(AppWorkPath)
  732. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  733. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  734. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  735. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  736. if !filepath.IsAbs(PprofDataPath) {
  737. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  738. }
  739. switch sec.Key("LANDING_PAGE").MustString("home") {
  740. case "explore":
  741. LandingPageURL = LandingPageExplore
  742. case "organizations":
  743. LandingPageURL = LandingPageOrganizations
  744. default:
  745. LandingPageURL = LandingPageHome
  746. }
  747. if len(SSH.Domain) == 0 {
  748. SSH.Domain = Domain
  749. }
  750. SSH.RootPath = path.Join(homeDir, ".ssh")
  751. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  752. if len(serverCiphers) > 0 {
  753. SSH.ServerCiphers = serverCiphers
  754. }
  755. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  756. if len(serverKeyExchanges) > 0 {
  757. SSH.ServerKeyExchanges = serverKeyExchanges
  758. }
  759. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  760. if len(serverMACs) > 0 {
  761. SSH.ServerMACs = serverMACs
  762. }
  763. SSH.KeyTestPath = os.TempDir()
  764. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  765. log.Fatal(4, "Failed to map SSH settings: %v", err)
  766. }
  767. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  768. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  769. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  770. // When disable SSH, start builtin server value is ignored.
  771. if SSH.Disabled {
  772. SSH.StartBuiltinServer = false
  773. }
  774. if !SSH.Disabled && !SSH.StartBuiltinServer {
  775. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  776. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  777. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  778. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  779. }
  780. }
  781. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  782. SSH.MinimumKeySizes = map[string]int{}
  783. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  784. for _, key := range minimumKeySizes {
  785. if key.MustInt() != -1 {
  786. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  787. }
  788. }
  789. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  790. SSH.CreateAuthorizedKeysFile = sec.Key("SSH_CREATE_AUTHORIZED_KEYS_FILE").MustBool(true)
  791. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  792. sec = Cfg.Section("server")
  793. if err = sec.MapTo(&LFS); err != nil {
  794. log.Fatal(4, "Failed to map LFS settings: %v", err)
  795. }
  796. LFS.ContentPath = sec.Key("LFS_CONTENT_PATH").MustString(filepath.Join(AppDataPath, "lfs"))
  797. if !filepath.IsAbs(LFS.ContentPath) {
  798. LFS.ContentPath = filepath.Join(AppWorkPath, LFS.ContentPath)
  799. }
  800. LFS.HTTPAuthExpiry = sec.Key("LFS_HTTP_AUTH_EXPIRY").MustDuration(20 * time.Minute)
  801. if LFS.StartServer {
  802. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  803. log.Fatal(4, "Failed to create '%s': %v", LFS.ContentPath, err)
  804. }
  805. LFS.JWTSecretBytes = make([]byte, 32)
  806. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  807. if err != nil || n != 32 {
  808. LFS.JWTSecretBase64, err = generate.NewLfsJwtSecret()
  809. if err != nil {
  810. log.Fatal(4, "Error generating JWT Secret for custom config: %v", err)
  811. return
  812. }
  813. // Save secret
  814. cfg := ini.Empty()
  815. if com.IsFile(CustomConf) {
  816. // Keeps custom settings if there is already something.
  817. if err := cfg.Append(CustomConf); err != nil {
  818. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  819. }
  820. }
  821. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  822. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  823. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  824. }
  825. if err := cfg.SaveTo(CustomConf); err != nil {
  826. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  827. return
  828. }
  829. }
  830. //Disable LFS client hooks if installed for the current OS user
  831. //Needs at least git v2.1.2
  832. binVersion, err := git.BinVersion()
  833. if err != nil {
  834. log.Fatal(4, "Error retrieving git version: %v", err)
  835. }
  836. splitVersion := strings.SplitN(binVersion, ".", 4)
  837. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  838. if err != nil {
  839. log.Fatal(4, "Error parsing git major version: %v", err)
  840. }
  841. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  842. if err != nil {
  843. log.Fatal(4, "Error parsing git minor version: %v", err)
  844. }
  845. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  846. if err != nil {
  847. log.Fatal(4, "Error parsing git revision version: %v", err)
  848. }
  849. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  850. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  851. LFS.StartServer = false
  852. log.Error(4, "LFS server support needs at least Git v2.1.2")
  853. } else {
  854. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  855. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  856. }
  857. }
  858. sec = Cfg.Section("security")
  859. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  860. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  861. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  862. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  863. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  864. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  865. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  866. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  867. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(false)
  868. InternalToken = sec.Key("INTERNAL_TOKEN").String()
  869. if len(InternalToken) == 0 {
  870. InternalToken, err = generate.NewInternalToken()
  871. if err != nil {
  872. log.Fatal(4, "Error generate internal token: %v", err)
  873. }
  874. // Save secret
  875. cfgSave := ini.Empty()
  876. if com.IsFile(CustomConf) {
  877. // Keeps custom settings if there is already something.
  878. if err := cfgSave.Append(CustomConf); err != nil {
  879. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  880. }
  881. }
  882. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(InternalToken)
  883. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  884. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  885. }
  886. if err := cfgSave.SaveTo(CustomConf); err != nil {
  887. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  888. }
  889. }
  890. IterateBufferSize = Cfg.Section("database").Key("ITERATE_BUFFER_SIZE").MustInt(50)
  891. LogSQL = Cfg.Section("database").Key("LOG_SQL").MustBool(true)
  892. sec = Cfg.Section("attachment")
  893. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  894. if !filepath.IsAbs(AttachmentPath) {
  895. AttachmentPath = path.Join(AppWorkPath, AttachmentPath)
  896. }
  897. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png,application/zip,application/gzip"), "|", ",", -1)
  898. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  899. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  900. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  901. TimeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("RFC1123")
  902. TimeFormat = map[string]string{
  903. "ANSIC": time.ANSIC,
  904. "UnixDate": time.UnixDate,
  905. "RubyDate": time.RubyDate,
  906. "RFC822": time.RFC822,
  907. "RFC822Z": time.RFC822Z,
  908. "RFC850": time.RFC850,
  909. "RFC1123": time.RFC1123,
  910. "RFC1123Z": time.RFC1123Z,
  911. "RFC3339": time.RFC3339,
  912. "RFC3339Nano": time.RFC3339Nano,
  913. "Kitchen": time.Kitchen,
  914. "Stamp": time.Stamp,
  915. "StampMilli": time.StampMilli,
  916. "StampMicro": time.StampMicro,
  917. "StampNano": time.StampNano,
  918. }[TimeFormatKey]
  919. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  920. if len(TimeFormat) == 0 {
  921. TimeFormat = TimeFormatKey
  922. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  923. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  924. log.Fatal(4, "Can't create time properly, please check your time format has 2006, 01, 02, 15, 04 and 05")
  925. }
  926. log.Trace("Custom TimeFormat: %s", TimeFormat)
  927. }
  928. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  929. // Does not check run user when the install lock is off.
  930. if InstallLock {
  931. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  932. if !match {
  933. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  934. }
  935. }
  936. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  937. // Determine and create root git repository path.
  938. sec = Cfg.Section("repository")
  939. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  940. Repository.UseCompatSSHURI = sec.Key("USE_COMPAT_SSH_URI").MustBool()
  941. Repository.MaxCreationLimit = sec.Key("MAX_CREATION_LIMIT").MustInt(-1)
  942. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  943. forcePathSeparator(RepoRootPath)
  944. if !filepath.IsAbs(RepoRootPath) {
  945. RepoRootPath = filepath.Join(AppWorkPath, RepoRootPath)
  946. } else {
  947. RepoRootPath = filepath.Clean(RepoRootPath)
  948. }
  949. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  950. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  951. log.Fatal(4, "Failed to map Repository settings: %v", err)
  952. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  953. log.Fatal(4, "Failed to map Repository.Editor settings: %v", err)
  954. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  955. log.Fatal(4, "Failed to map Repository.Upload settings: %v", err)
  956. } else if err = Cfg.Section("repository.local").MapTo(&Repository.Local); err != nil {
  957. log.Fatal(4, "Failed to map Repository.Local settings: %v", err)
  958. } else if err = Cfg.Section("repository.pull-request").MapTo(&Repository.PullRequest); err != nil {
  959. log.Fatal(4, "Failed to map Repository.PullRequest settings: %v", err)
  960. }
  961. if !filepath.IsAbs(Repository.Upload.TempPath) {
  962. Repository.Upload.TempPath = path.Join(AppWorkPath, Repository.Upload.TempPath)
  963. }
  964. sec = Cfg.Section("picture")
  965. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  966. forcePathSeparator(AvatarUploadPath)
  967. if !filepath.IsAbs(AvatarUploadPath) {
  968. AvatarUploadPath = path.Join(AppWorkPath, AvatarUploadPath)
  969. }
  970. AvatarMaxWidth = sec.Key("AVATAR_MAX_WIDTH").MustInt(4096)
  971. AvatarMaxHeight = sec.Key("AVATAR_MAX_HEIGHT").MustInt(3072)
  972. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  973. case "duoshuo":
  974. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  975. case "gravatar":
  976. GravatarSource = "https://secure.gravatar.com/avatar/"
  977. case "libravatar":
  978. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  979. default:
  980. GravatarSource = source
  981. }
  982. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  983. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(!InstallLock)
  984. if OfflineMode {
  985. DisableGravatar = true
  986. EnableFederatedAvatar = false
  987. }
  988. if DisableGravatar {
  989. EnableFederatedAvatar = false
  990. }
  991. if EnableFederatedAvatar || !DisableGravatar {
  992. GravatarSourceURL, err = url.Parse(GravatarSource)
  993. if err != nil {
  994. log.Fatal(4, "Failed to parse Gravatar URL(%s): %v",
  995. GravatarSource, err)
  996. }
  997. }
  998. if EnableFederatedAvatar {
  999. LibravatarService = libravatar.New()
  1000. if GravatarSourceURL.Scheme == "https" {
  1001. LibravatarService.SetUseHTTPS(true)
  1002. LibravatarService.SetSecureFallbackHost(GravatarSourceURL.Host)
  1003. } else {
  1004. LibravatarService.SetUseHTTPS(false)
  1005. LibravatarService.SetFallbackHost(GravatarSourceURL.Host)
  1006. }
  1007. }
  1008. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  1009. log.Fatal(4, "Failed to map UI settings: %v", err)
  1010. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  1011. log.Fatal(4, "Failed to map Markdown settings: %v", err)
  1012. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  1013. log.Fatal(4, "Fail to map Admin settings: %v", err)
  1014. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  1015. log.Fatal(4, "Failed to map Cron settings: %v", err)
  1016. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  1017. log.Fatal(4, "Failed to map Git settings: %v", err)
  1018. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  1019. log.Fatal(4, "Failed to map API settings: %v", err)
  1020. }
  1021. sec = Cfg.Section("mirror")
  1022. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  1023. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  1024. if Mirror.MinInterval.Minutes() < 1 {
  1025. log.Warn("Mirror.MinInterval is too low")
  1026. Mirror.MinInterval = 1 * time.Minute
  1027. }
  1028. if Mirror.DefaultInterval < Mirror.MinInterval {
  1029. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  1030. Mirror.DefaultInterval = time.Hour * 8
  1031. }
  1032. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  1033. if len(Langs) == 0 {
  1034. Langs = defaultLangs
  1035. }
  1036. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  1037. if len(Names) == 0 {
  1038. Names = defaultLangNames
  1039. }
  1040. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  1041. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  1042. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  1043. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  1044. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  1045. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  1046. extensionReg := regexp.MustCompile(`\.\w`)
  1047. for _, sec := range Cfg.Section("markup").ChildSections() {
  1048. name := strings.TrimPrefix(sec.Name(), "markup.")
  1049. if name == "" {
  1050. log.Warn("name is empty, markup " + sec.Name() + "ignored")
  1051. continue
  1052. }
  1053. extensions := sec.Key("FILE_EXTENSIONS").Strings(",")
  1054. var exts = make([]string, 0, len(extensions))
  1055. for _, extension := range extensions {
  1056. if !extensionReg.MatchString(extension) {
  1057. log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored")
  1058. } else {
  1059. exts = append(exts, extension)
  1060. }
  1061. }
  1062. if len(exts) == 0 {
  1063. log.Warn(sec.Name() + " file extension is empty, markup " + name + " ignored")
  1064. continue
  1065. }
  1066. command := sec.Key("RENDER_COMMAND").MustString("")
  1067. if command == "" {
  1068. log.Warn(" RENDER_COMMAND is empty, markup " + name + " ignored")
  1069. continue
  1070. }
  1071. ExternalMarkupParsers = append(ExternalMarkupParsers, MarkupParser{
  1072. Enabled: sec.Key("ENABLED").MustBool(false),
  1073. MarkupName: name,
  1074. FileExtensions: exts,
  1075. Command: command,
  1076. IsInputFile: sec.Key("IS_INPUT_FILE").MustBool(false),
  1077. })
  1078. }
  1079. sec = Cfg.Section("U2F")
  1080. U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimRight(AppURL, "/")))
  1081. U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimRight(AppURL, "/"))
  1082. }
  1083. // Service settings
  1084. var Service struct {
  1085. ActiveCodeLives int
  1086. ResetPwdCodeLives int
  1087. RegisterEmailConfirm bool
  1088. DisableRegistration bool
  1089. AllowOnlyExternalRegistration bool
  1090. ShowRegistrationButton bool
  1091. RequireSignInView bool
  1092. EnableNotifyMail bool
  1093. EnableReverseProxyAuth bool
  1094. EnableReverseProxyAutoRegister bool
  1095. EnableCaptcha bool
  1096. CaptchaType string
  1097. RecaptchaSecret string
  1098. RecaptchaSitekey string
  1099. DefaultKeepEmailPrivate bool
  1100. DefaultAllowCreateOrganization bool
  1101. EnableTimetracking bool
  1102. DefaultEnableTimetracking bool
  1103. DefaultEnableDependencies bool
  1104. DefaultAllowOnlyContributorsToTrackTime bool
  1105. NoReplyAddress string
  1106. EnableUserHeatmap bool
  1107. // OpenID settings
  1108. EnableOpenIDSignIn bool
  1109. EnableOpenIDSignUp bool
  1110. OpenIDWhitelist []*regexp.Regexp
  1111. OpenIDBlacklist []*regexp.Regexp
  1112. }
  1113. func newService() {
  1114. sec := Cfg.Section("service")
  1115. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  1116. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  1117. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  1118. Service.AllowOnlyExternalRegistration = sec.Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").MustBool()
  1119. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!(Service.DisableRegistration || Service.AllowOnlyExternalRegistration))
  1120. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  1121. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  1122. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  1123. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool(false)
  1124. Service.CaptchaType = sec.Key("CAPTCHA_TYPE").MustString(ImageCaptcha)
  1125. Service.RecaptchaSecret = sec.Key("RECAPTCHA_SECRET").MustString("")
  1126. Service.RecaptchaSitekey = sec.Key("RECAPTCHA_SITEKEY").MustString("")
  1127. Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
  1128. Service.DefaultAllowCreateOrganization = sec.Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").MustBool(true)
  1129. Service.EnableTimetracking = sec.Key("ENABLE_TIMETRACKING").MustBool(true)
  1130. if Service.EnableTimetracking {
  1131. Service.DefaultEnableTimetracking = sec.Key("DEFAULT_ENABLE_TIMETRACKING").MustBool(true)
  1132. }
  1133. Service.DefaultEnableDependencies = sec.Key("DEFAULT_ENABLE_DEPENDENCIES").MustBool(true)
  1134. Service.DefaultAllowOnlyContributorsToTrackTime = sec.Key("DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME").MustBool(true)
  1135. Service.NoReplyAddress = sec.Key("NO_REPLY_ADDRESS").MustString("noreply.example.org")
  1136. Service.EnableUserHeatmap = sec.Key("ENABLE_USER_HEATMAP").MustBool(true)
  1137. sec = Cfg.Section("openid")
  1138. Service.EnableOpenIDSignIn = sec.Key("ENABLE_OPENID_SIGNIN").MustBool(!InstallLock)
  1139. Service.EnableOpenIDSignUp = sec.Key("ENABLE_OPENID_SIGNUP").MustBool(!Service.DisableRegistration && Service.EnableOpenIDSignIn)
  1140. pats := sec.Key("WHITELISTED_URIS").Strings(" ")
  1141. if len(pats) != 0 {
  1142. Service.OpenIDWhitelist = make([]*regexp.Regexp, len(pats))
  1143. for i, p := range pats {
  1144. Service.OpenIDWhitelist[i] = regexp.MustCompilePOSIX(p)
  1145. }
  1146. }
  1147. pats = sec.Key("BLACKLISTED_URIS").Strings(" ")
  1148. if len(pats) != 0 {
  1149. Service.OpenIDBlacklist = make([]*regexp.Regexp, len(pats))
  1150. for i, p := range pats {
  1151. Service.OpenIDBlacklist[i] = regexp.MustCompilePOSIX(p)
  1152. }
  1153. }
  1154. }
  1155. var logLevels = map[string]string{
  1156. "Trace": "0",
  1157. "Debug": "1",
  1158. "Info": "2",
  1159. "Warn": "3",
  1160. "Error": "4",
  1161. "Critical": "5",
  1162. }
  1163. func getLogLevel(section string, key string, defaultValue string) string {
  1164. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  1165. return Cfg.Section(section).Key(key).In(defaultValue, validLevels)
  1166. }
  1167. func newLogService() {
  1168. log.Info("Gitea v%s%s", AppVer, AppBuiltWith)
  1169. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1170. LogConfigs = make([]string, len(LogModes))
  1171. useConsole := false
  1172. for i := 0; i < len(LogModes); i++ {
  1173. LogModes[i] = strings.TrimSpace(LogModes[i])
  1174. if LogModes[i] == "console" {
  1175. useConsole = true
  1176. }
  1177. }
  1178. if !useConsole {
  1179. log.DelLogger("console")
  1180. }
  1181. for i, mode := range LogModes {
  1182. sec, err := Cfg.GetSection("log." + mode)
  1183. if err != nil {
  1184. sec, _ = Cfg.NewSection("log." + mode)
  1185. }
  1186. // Log level.
  1187. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1188. level, ok := logLevels[levelName]
  1189. if !ok {
  1190. log.Fatal(4, "Unknown log level: %s", levelName)
  1191. }
  1192. // Generate log configuration.
  1193. switch mode {
  1194. case "console":
  1195. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  1196. case "file":
  1197. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gitea.log"))
  1198. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1199. panic(err.Error())
  1200. }
  1201. LogConfigs[i] = fmt.Sprintf(
  1202. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1203. logPath,
  1204. sec.Key("LOG_ROTATE").MustBool(true),
  1205. sec.Key("MAX_LINES").MustInt(1000000),
  1206. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1207. sec.Key("DAILY_ROTATE").MustBool(true),
  1208. sec.Key("MAX_DAYS").MustInt(7))
  1209. case "conn":
  1210. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1211. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1212. sec.Key("RECONNECT").MustBool(),
  1213. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1214. sec.Key("ADDR").MustString(":7020"))
  1215. case "smtp":
  1216. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  1217. sec.Key("USER").MustString("example@example.com"),
  1218. sec.Key("PASSWD").MustString("******"),
  1219. sec.Key("HOST").MustString("127.0.0.1:25"),
  1220. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  1221. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1222. case "database":
  1223. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1224. sec.Key("DRIVER").String(),
  1225. sec.Key("CONN").String())
  1226. }
  1227. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  1228. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  1229. }
  1230. }
  1231. // NewXORMLogService initializes xorm logger service
  1232. func NewXORMLogService(disableConsole bool) {
  1233. logModes := strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1234. var logConfigs string
  1235. for _, mode := range logModes {
  1236. mode = strings.TrimSpace(mode)
  1237. if disableConsole && mode == "console" {
  1238. continue
  1239. }
  1240. sec, err := Cfg.GetSection("log." + mode)
  1241. if err != nil {
  1242. sec, _ = Cfg.NewSection("log." + mode)
  1243. }
  1244. // Log level.
  1245. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1246. level, ok := logLevels[levelName]
  1247. if !ok {
  1248. log.Fatal(4, "Unknown log level: %s", levelName)
  1249. }
  1250. // Generate log configuration.
  1251. switch mode {
  1252. case "console":
  1253. logConfigs = fmt.Sprintf(`{"level":%s}`, level)
  1254. case "file":
  1255. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "xorm.log"))
  1256. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1257. panic(err.Error())
  1258. }
  1259. logPath = path.Join(filepath.Dir(logPath), "xorm.log")
  1260. logConfigs = fmt.Sprintf(
  1261. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1262. logPath,
  1263. sec.Key("LOG_ROTATE").MustBool(true),
  1264. sec.Key("MAX_LINES").MustInt(1000000),
  1265. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1266. sec.Key("DAILY_ROTATE").MustBool(true),
  1267. sec.Key("MAX_DAYS").MustInt(7))
  1268. case "conn":
  1269. logConfigs = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1270. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1271. sec.Key("RECONNECT").MustBool(),
  1272. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1273. sec.Key("ADDR").MustString(":7020"))
  1274. case "smtp":
  1275. logConfigs = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  1276. sec.Key("USER").MustString("example@example.com"),
  1277. sec.Key("PASSWD").MustString("******"),
  1278. sec.Key("HOST").MustString("127.0.0.1:25"),
  1279. sec.Key("RECEIVERS").MustString("[]"),
  1280. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1281. case "database":
  1282. logConfigs = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1283. sec.Key("DRIVER").String(),
  1284. sec.Key("CONN").String())
  1285. }
  1286. log.NewXORMLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, logConfigs)
  1287. if !disableConsole {
  1288. log.Info("XORM Log Mode: %s(%s)", strings.Title(mode), levelName)
  1289. }
  1290. var lvl core.LogLevel
  1291. switch levelName {
  1292. case "Trace", "Debug":
  1293. lvl = core.LOG_DEBUG
  1294. case "Info":
  1295. lvl = core.LOG_INFO
  1296. case "Warn":
  1297. lvl = core.LOG_WARNING
  1298. case "Error", "Critical":
  1299. lvl = core.LOG_ERR
  1300. }
  1301. log.XORMLogger.SetLevel(lvl)
  1302. }
  1303. if len(logConfigs) == 0 {
  1304. log.DiscardXORMLogger()
  1305. }
  1306. }
  1307. // Cache represents cache settings
  1308. type Cache struct {
  1309. Adapter string
  1310. Interval int
  1311. Conn string
  1312. TTL time.Duration
  1313. }
  1314. var (
  1315. // CacheService the global cache
  1316. CacheService *Cache
  1317. )
  1318. func newCacheService() {
  1319. sec := Cfg.Section("cache")
  1320. CacheService = &Cache{
  1321. Adapter: sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"}),
  1322. }
  1323. switch CacheService.Adapter {
  1324. case "memory":
  1325. CacheService.Interval = sec.Key("INTERVAL").MustInt(60)
  1326. case "redis", "memcache":
  1327. CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ")
  1328. default:
  1329. log.Fatal(4, "Unknown cache adapter: %s", CacheService.Adapter)
  1330. }
  1331. CacheService.TTL = sec.Key("ITEM_TTL").MustDuration(16 * time.Hour)
  1332. log.Info("Cache Service Enabled")
  1333. }
  1334. func newSessionService() {
  1335. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  1336. []string{"memory", "file", "redis", "mysql"})
  1337. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").MustString(path.Join(AppDataPath, "sessions")), "\" ")
  1338. if SessionConfig.Provider == "file" && !filepath.IsAbs(SessionConfig.ProviderConfig) {
  1339. SessionConfig.ProviderConfig = path.Join(AppWorkPath, SessionConfig.ProviderConfig)
  1340. }
  1341. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  1342. SessionConfig.CookiePath = AppSubURL
  1343. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  1344. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  1345. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  1346. log.Info("Session Service Enabled")
  1347. }
  1348. // Mailer represents mail service.
  1349. type Mailer struct {
  1350. // Mailer
  1351. QueueLength int
  1352. Name string
  1353. From string
  1354. FromName string
  1355. FromEmail string
  1356. SendAsPlainText bool
  1357. // SMTP sender
  1358. Host string
  1359. User, Passwd string
  1360. DisableHelo bool
  1361. HeloHostname string
  1362. SkipVerify bool
  1363. UseCertificate bool
  1364. CertFile, KeyFile string
  1365. // Sendmail sender
  1366. UseSendmail bool
  1367. SendmailPath string
  1368. SendmailArgs []string
  1369. }
  1370. var (
  1371. // MailService the global mailer
  1372. MailService *Mailer
  1373. )
  1374. func newMailService() {
  1375. sec := Cfg.Section("mailer")
  1376. // Check mailer setting.
  1377. if !sec.Key("ENABLED").MustBool() {
  1378. return
  1379. }
  1380. MailService = &Mailer{
  1381. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  1382. Name: sec.Key("NAME").MustString(AppName),
  1383. SendAsPlainText: sec.Key("SEND_AS_PLAIN_TEXT").MustBool(false),
  1384. Host: sec.Key("HOST").String(),
  1385. User: sec.Key("USER").String(),
  1386. Passwd: sec.Key("PASSWD").String(),
  1387. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  1388. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  1389. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  1390. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  1391. CertFile: sec.Key("CERT_FILE").String(),
  1392. KeyFile: sec.Key("KEY_FILE").String(),
  1393. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  1394. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  1395. }
  1396. MailService.From = sec.Key("FROM").MustString(MailService.User)
  1397. if sec.HasKey("ENABLE_HTML_ALTERNATIVE") {
  1398. log.Warn("ENABLE_HTML_ALTERNATIVE is deprecated, use SEND_AS_PLAIN_TEXT")
  1399. MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false)
  1400. }
  1401. parsed, err := mail.ParseAddress(MailService.From)
  1402. if err != nil {
  1403. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1404. }
  1405. MailService.FromName = parsed.Name
  1406. MailService.FromEmail = parsed.Address
  1407. if MailService.UseSendmail {
  1408. MailService.SendmailArgs, err = shellquote.Split(sec.Key("SENDMAIL_ARGS").String())
  1409. if err != nil {
  1410. log.Error(4, "Failed to parse Sendmail args: %v", CustomConf, err)
  1411. }
  1412. }
  1413. log.Info("Mail Service Enabled")
  1414. }
  1415. func newRegisterMailService() {
  1416. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1417. return
  1418. } else if MailService == nil {
  1419. log.Warn("Register Mail Service: Mail Service is not enabled")
  1420. return
  1421. }
  1422. Service.RegisterEmailConfirm = true
  1423. log.Info("Register Mail Service Enabled")
  1424. }
  1425. func newNotifyMailService() {
  1426. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1427. return
  1428. } else if MailService == nil {
  1429. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1430. return
  1431. }
  1432. Service.EnableNotifyMail = true
  1433. log.Info("Notify Mail Service Enabled")
  1434. }
  1435. func newWebhookService() {
  1436. sec := Cfg.Section("webhook")
  1437. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1438. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1439. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1440. Webhook.Types = []string{"gitea", "gogs", "slack", "discord", "dingtalk"}
  1441. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1442. }
  1443. // NewServices initializes the services
  1444. func NewServices() {
  1445. newService()
  1446. newLogService()
  1447. NewXORMLogService(false)
  1448. newCacheService()
  1449. newSessionService()
  1450. newMailService()
  1451. newRegisterMailService()
  1452. newNotifyMailService()
  1453. newWebhookService()
  1454. }