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 42KB

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