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

setting.go 46KB

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