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

setting.go 43KB

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