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

setting.go 39KB

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