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

setting.go 42KB

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