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

setting.go 46KB

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