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

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