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

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