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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. "encoding/base64"
  8. "fmt"
  9. "math"
  10. "net"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "text/template"
  20. "time"
  21. "code.gitea.io/gitea/modules/container"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/json"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/user"
  26. "code.gitea.io/gitea/modules/util"
  27. gossh "golang.org/x/crypto/ssh"
  28. ini "gopkg.in/ini.v1"
  29. )
  30. // Scheme describes protocol types
  31. type Scheme string
  32. // enumerates all the scheme types
  33. const (
  34. HTTP Scheme = "http"
  35. HTTPS Scheme = "https"
  36. FCGI Scheme = "fcgi"
  37. FCGIUnix Scheme = "fcgi+unix"
  38. HTTPUnix Scheme = "http+unix"
  39. )
  40. // LandingPage describes the default page
  41. type LandingPage string
  42. // enumerates all the landing page types
  43. const (
  44. LandingPageHome LandingPage = "/"
  45. LandingPageExplore LandingPage = "/explore"
  46. LandingPageOrganizations LandingPage = "/explore/organizations"
  47. LandingPageLogin LandingPage = "/user/login"
  48. )
  49. // enumerates all the types of captchas
  50. const (
  51. ImageCaptcha = "image"
  52. ReCaptcha = "recaptcha"
  53. HCaptcha = "hcaptcha"
  54. MCaptcha = "mcaptcha"
  55. )
  56. // settings
  57. var (
  58. // AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
  59. AppVer string
  60. // AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
  61. AppBuiltWith string
  62. // AppStartTime store time gitea has started
  63. AppStartTime time.Time
  64. // AppName is the Application name, used in the page title.
  65. // It maps to ini:"APP_NAME"
  66. AppName string
  67. // AppURL is the Application ROOT_URL. It always has a '/' suffix
  68. // It maps to ini:"ROOT_URL"
  69. AppURL string
  70. // AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
  71. // This value is empty if site does not have sub-url.
  72. AppSubURL string
  73. // AppPath represents the path to the gitea binary
  74. AppPath string
  75. // AppWorkPath is the "working directory" of Gitea. It maps to the environment variable GITEA_WORK_DIR.
  76. // If that is not set it is the default set here by the linker or failing that the directory of AppPath.
  77. //
  78. // AppWorkPath is used as the base path for several other paths.
  79. AppWorkPath string
  80. // AppDataPath is the default path for storing data.
  81. // It maps to ini:"APP_DATA_PATH" in [server] and defaults to AppWorkPath + "/data"
  82. AppDataPath string
  83. // LocalURL is the url for locally running applications to contact Gitea. It always has a '/' suffix
  84. // It maps to ini:"LOCAL_ROOT_URL" in [server]
  85. LocalURL string
  86. // AssetVersion holds a opaque value that is used for cache-busting assets
  87. AssetVersion string
  88. // Server settings
  89. Protocol Scheme
  90. UseProxyProtocol bool // `ini:"USE_PROXY_PROTOCOL"`
  91. ProxyProtocolTLSBridging bool //`ini:"PROXY_PROTOCOL_TLS_BRIDGING"`
  92. ProxyProtocolHeaderTimeout time.Duration
  93. ProxyProtocolAcceptUnknown bool
  94. Domain string
  95. HTTPAddr string
  96. HTTPPort string
  97. LocalUseProxyProtocol bool
  98. RedirectOtherPort bool
  99. RedirectorUseProxyProtocol bool
  100. PortToRedirect string
  101. OfflineMode bool
  102. CertFile string
  103. KeyFile string
  104. StaticRootPath string
  105. StaticCacheTime time.Duration
  106. EnableGzip bool
  107. LandingPageURL LandingPage
  108. LandingPageCustom string
  109. UnixSocketPermission uint32
  110. EnablePprof bool
  111. PprofDataPath string
  112. EnableAcme bool
  113. AcmeTOS bool
  114. AcmeLiveDirectory string
  115. AcmeEmail string
  116. AcmeURL string
  117. AcmeCARoot string
  118. SSLMinimumVersion string
  119. SSLMaximumVersion string
  120. SSLCurvePreferences []string
  121. SSLCipherSuites []string
  122. GracefulRestartable bool
  123. GracefulHammerTime time.Duration
  124. StartupTimeout time.Duration
  125. PerWriteTimeout = 30 * time.Second
  126. PerWritePerKbTimeout = 10 * time.Second
  127. StaticURLPrefix string
  128. AbsoluteAssetURL string
  129. SSH = struct {
  130. Disabled bool `ini:"DISABLE_SSH"`
  131. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  132. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  133. UseProxyProtocol bool `ini:"SSH_SERVER_USE_PROXY_PROTOCOL"`
  134. Domain string `ini:"SSH_DOMAIN"`
  135. Port int `ini:"SSH_PORT"`
  136. User string `ini:"SSH_USER"`
  137. ListenHost string `ini:"SSH_LISTEN_HOST"`
  138. ListenPort int `ini:"SSH_LISTEN_PORT"`
  139. RootPath string `ini:"SSH_ROOT_PATH"`
  140. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  141. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  142. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  143. ServerHostKeys []string `ini:"SSH_SERVER_HOST_KEYS"`
  144. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  145. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  146. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  147. AuthorizedPrincipalsBackup bool `ini:"SSH_AUTHORIZED_PRINCIPALS_BACKUP"`
  148. AuthorizedKeysCommandTemplate string `ini:"SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE"`
  149. AuthorizedKeysCommandTemplateTemplate *template.Template `ini:"-"`
  150. MinimumKeySizeCheck bool `ini:"-"`
  151. MinimumKeySizes map[string]int `ini:"-"`
  152. CreateAuthorizedKeysFile bool `ini:"SSH_CREATE_AUTHORIZED_KEYS_FILE"`
  153. CreateAuthorizedPrincipalsFile bool `ini:"SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE"`
  154. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  155. AuthorizedPrincipalsAllow []string `ini:"SSH_AUTHORIZED_PRINCIPALS_ALLOW"`
  156. AuthorizedPrincipalsEnabled bool `ini:"-"`
  157. TrustedUserCAKeys []string `ini:"SSH_TRUSTED_USER_CA_KEYS"`
  158. TrustedUserCAKeysFile string `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
  159. TrustedUserCAKeysParsed []gossh.PublicKey `ini:"-"`
  160. PerWriteTimeout time.Duration `ini:"SSH_PER_WRITE_TIMEOUT"`
  161. PerWritePerKbTimeout time.Duration `ini:"SSH_PER_WRITE_PER_KB_TIMEOUT"`
  162. }{
  163. Disabled: false,
  164. StartBuiltinServer: false,
  165. Domain: "",
  166. Port: 22,
  167. ServerCiphers: []string{"chacha20-poly1305@openssh.com", "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "aes256-gcm@openssh.com"},
  168. ServerKeyExchanges: []string{"curve25519-sha256", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "diffie-hellman-group14-sha256", "diffie-hellman-group14-sha1"},
  169. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1"},
  170. KeygenPath: "ssh-keygen",
  171. MinimumKeySizeCheck: true,
  172. MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2047},
  173. ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
  174. AuthorizedKeysCommandTemplate: "{{.AppPath}} --config={{.CustomConf}} serv key-{{.Key.ID}}",
  175. PerWriteTimeout: PerWriteTimeout,
  176. PerWritePerKbTimeout: PerWritePerKbTimeout,
  177. }
  178. // Security settings
  179. InstallLock bool
  180. SecretKey string
  181. LogInRememberDays int
  182. CookieUserName string
  183. CookieRememberName string
  184. ReverseProxyAuthUser string
  185. ReverseProxyAuthEmail string
  186. ReverseProxyAuthFullName string
  187. ReverseProxyLimit int
  188. ReverseProxyTrustedProxies []string
  189. MinPasswordLength int
  190. ImportLocalPaths bool
  191. DisableGitHooks bool
  192. DisableWebhooks bool
  193. OnlyAllowPushIfGiteaEnvironmentSet bool
  194. PasswordComplexity []string
  195. PasswordHashAlgo string
  196. PasswordCheckPwn bool
  197. SuccessfulTokensCacheSize int
  198. Camo = struct {
  199. Enabled bool
  200. ServerURL string `ini:"SERVER_URL"`
  201. HMACKey string `ini:"HMAC_KEY"`
  202. Allways bool
  203. }{}
  204. // UI settings
  205. UI = struct {
  206. ExplorePagingNum int
  207. SitemapPagingNum int
  208. IssuePagingNum int
  209. RepoSearchPagingNum int
  210. MembersPagingNum int
  211. FeedMaxCommitNum int
  212. FeedPagingNum int
  213. PackagesPagingNum int
  214. GraphMaxCommitNum int
  215. CodeCommentLines int
  216. ReactionMaxUserNum int
  217. ThemeColorMetaTag string
  218. MaxDisplayFileSize int64
  219. ShowUserEmail bool
  220. DefaultShowFullName bool
  221. DefaultTheme string
  222. Themes []string
  223. Reactions []string
  224. ReactionsLookup container.Set[string] `ini:"-"`
  225. CustomEmojis []string
  226. CustomEmojisMap map[string]string `ini:"-"`
  227. SearchRepoDescription bool
  228. UseServiceWorker bool
  229. OnlyShowRelevantRepos bool
  230. Notification struct {
  231. MinTimeout time.Duration
  232. TimeoutStep time.Duration
  233. MaxTimeout time.Duration
  234. EventSourceUpdateTime time.Duration
  235. } `ini:"ui.notification"`
  236. SVG struct {
  237. Enabled bool `ini:"ENABLE_RENDER"`
  238. } `ini:"ui.svg"`
  239. CSV struct {
  240. MaxFileSize int64
  241. } `ini:"ui.csv"`
  242. Admin struct {
  243. UserPagingNum int
  244. RepoPagingNum int
  245. NoticePagingNum int
  246. OrgPagingNum int
  247. } `ini:"ui.admin"`
  248. User struct {
  249. RepoPagingNum int
  250. } `ini:"ui.user"`
  251. Meta struct {
  252. Author string
  253. Description string
  254. Keywords string
  255. } `ini:"ui.meta"`
  256. }{
  257. ExplorePagingNum: 20,
  258. SitemapPagingNum: 20,
  259. IssuePagingNum: 20,
  260. RepoSearchPagingNum: 20,
  261. MembersPagingNum: 20,
  262. FeedMaxCommitNum: 5,
  263. FeedPagingNum: 20,
  264. PackagesPagingNum: 20,
  265. GraphMaxCommitNum: 100,
  266. CodeCommentLines: 4,
  267. ReactionMaxUserNum: 10,
  268. ThemeColorMetaTag: `#6cc644`,
  269. MaxDisplayFileSize: 8388608,
  270. DefaultTheme: `auto`,
  271. Themes: []string{`auto`, `gitea`, `arc-green`},
  272. Reactions: []string{`+1`, `-1`, `laugh`, `hooray`, `confused`, `heart`, `rocket`, `eyes`},
  273. CustomEmojis: []string{`git`, `gitea`, `codeberg`, `gitlab`, `github`, `gogs`},
  274. CustomEmojisMap: map[string]string{"git": ":git:", "gitea": ":gitea:", "codeberg": ":codeberg:", "gitlab": ":gitlab:", "github": ":github:", "gogs": ":gogs:"},
  275. Notification: struct {
  276. MinTimeout time.Duration
  277. TimeoutStep time.Duration
  278. MaxTimeout time.Duration
  279. EventSourceUpdateTime time.Duration
  280. }{
  281. MinTimeout: 10 * time.Second,
  282. TimeoutStep: 10 * time.Second,
  283. MaxTimeout: 60 * time.Second,
  284. EventSourceUpdateTime: 10 * time.Second,
  285. },
  286. SVG: struct {
  287. Enabled bool `ini:"ENABLE_RENDER"`
  288. }{
  289. Enabled: true,
  290. },
  291. CSV: struct {
  292. MaxFileSize int64
  293. }{
  294. MaxFileSize: 524288,
  295. },
  296. Admin: struct {
  297. UserPagingNum int
  298. RepoPagingNum int
  299. NoticePagingNum int
  300. OrgPagingNum int
  301. }{
  302. UserPagingNum: 50,
  303. RepoPagingNum: 50,
  304. NoticePagingNum: 25,
  305. OrgPagingNum: 50,
  306. },
  307. User: struct {
  308. RepoPagingNum int
  309. }{
  310. RepoPagingNum: 15,
  311. },
  312. Meta: struct {
  313. Author string
  314. Description string
  315. Keywords string
  316. }{
  317. Author: "Gitea - Git with a cup of tea",
  318. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  319. Keywords: "go,git,self-hosted,gitea",
  320. },
  321. }
  322. // Markdown settings
  323. Markdown = struct {
  324. EnableHardLineBreakInComments bool
  325. EnableHardLineBreakInDocuments bool
  326. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  327. FileExtensions []string
  328. EnableMath bool
  329. }{
  330. EnableHardLineBreakInComments: true,
  331. EnableHardLineBreakInDocuments: false,
  332. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  333. EnableMath: true,
  334. }
  335. // Admin settings
  336. Admin struct {
  337. DisableRegularOrgCreation bool
  338. DefaultEmailNotification string
  339. }
  340. // Log settings
  341. LogLevel log.Level
  342. StacktraceLogLevel string
  343. LogRootPath string
  344. EnableSSHLog bool
  345. EnableXORMLog bool
  346. DisableRouterLog bool
  347. EnableAccessLog bool
  348. AccessLogTemplate string
  349. // Time settings
  350. TimeFormat string
  351. // UILocation is the location on the UI, so that we can display the time on UI.
  352. DefaultUILocation = time.Local
  353. CSRFCookieName = "_csrf"
  354. CSRFCookieHTTPOnly = true
  355. ManifestData string
  356. // API settings
  357. API = struct {
  358. EnableSwagger bool
  359. SwaggerURL string
  360. MaxResponseItems int
  361. DefaultPagingNum int
  362. DefaultGitTreesPerPage int
  363. DefaultMaxBlobSize int64
  364. }{
  365. EnableSwagger: true,
  366. SwaggerURL: "",
  367. MaxResponseItems: 50,
  368. DefaultPagingNum: 30,
  369. DefaultGitTreesPerPage: 1000,
  370. DefaultMaxBlobSize: 10485760,
  371. }
  372. OAuth2 = struct {
  373. Enable bool
  374. AccessTokenExpirationTime int64
  375. RefreshTokenExpirationTime int64
  376. InvalidateRefreshTokens bool
  377. JWTSigningAlgorithm string `ini:"JWT_SIGNING_ALGORITHM"`
  378. JWTSecretBase64 string `ini:"JWT_SECRET"`
  379. JWTSigningPrivateKeyFile string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
  380. MaxTokenLength int
  381. }{
  382. Enable: true,
  383. AccessTokenExpirationTime: 3600,
  384. RefreshTokenExpirationTime: 730,
  385. InvalidateRefreshTokens: false,
  386. JWTSigningAlgorithm: "RS256",
  387. JWTSigningPrivateKeyFile: "jwt/private.pem",
  388. MaxTokenLength: math.MaxInt16,
  389. }
  390. // Metrics settings
  391. Metrics = struct {
  392. Enabled bool
  393. Token string
  394. EnabledIssueByLabel bool
  395. EnabledIssueByRepository bool
  396. }{
  397. Enabled: false,
  398. Token: "",
  399. EnabledIssueByLabel: false,
  400. EnabledIssueByRepository: false,
  401. }
  402. // I18n settings
  403. Langs []string
  404. Names []string
  405. // Highlight settings are loaded in modules/template/highlight.go
  406. // Other settings
  407. ShowFooterBranding bool
  408. ShowFooterVersion bool
  409. ShowFooterTemplateLoadTime bool
  410. EnableFeed bool
  411. // Global setting objects
  412. Cfg *ini.File
  413. CustomPath string // Custom directory path
  414. CustomConf string
  415. PIDFile = "/run/gitea.pid"
  416. WritePIDFile bool
  417. RunMode string
  418. IsProd bool
  419. RunUser string
  420. IsWindows bool
  421. HasRobotsTxt bool
  422. EnableSitemap bool
  423. InternalToken string // internal access token
  424. )
  425. func getAppPath() (string, error) {
  426. var appPath string
  427. var err error
  428. if IsWindows && filepath.IsAbs(os.Args[0]) {
  429. appPath = filepath.Clean(os.Args[0])
  430. } else {
  431. appPath, err = exec.LookPath(os.Args[0])
  432. }
  433. if err != nil {
  434. return "", err
  435. }
  436. appPath, err = filepath.Abs(appPath)
  437. if err != nil {
  438. return "", err
  439. }
  440. // Note: we don't use path.Dir here because it does not handle case
  441. // which path starts with two "/" in Windows: "//psf/Home/..."
  442. return strings.ReplaceAll(appPath, "\\", "/"), err
  443. }
  444. func getWorkPath(appPath string) string {
  445. workPath := AppWorkPath
  446. if giteaWorkPath, ok := os.LookupEnv("GITEA_WORK_DIR"); ok {
  447. workPath = giteaWorkPath
  448. }
  449. if len(workPath) == 0 {
  450. i := strings.LastIndex(appPath, "/")
  451. if i == -1 {
  452. workPath = appPath
  453. } else {
  454. workPath = appPath[:i]
  455. }
  456. }
  457. workPath = strings.ReplaceAll(workPath, "\\", "/")
  458. if !filepath.IsAbs(workPath) {
  459. log.Info("Provided work path %s is not absolute - will be made absolute against the current working directory", workPath)
  460. absPath, err := filepath.Abs(workPath)
  461. if err != nil {
  462. log.Error("Unable to absolute %s against the current working directory %v. Will absolute against the AppPath %s", workPath, err, appPath)
  463. workPath = filepath.Join(appPath, workPath)
  464. } else {
  465. workPath = absPath
  466. }
  467. }
  468. return strings.ReplaceAll(workPath, "\\", "/")
  469. }
  470. func init() {
  471. IsWindows = runtime.GOOS == "windows"
  472. // We can rely on log.CanColorStdout being set properly because modules/log/console_windows.go comes before modules/setting/setting.go lexicographically
  473. // By default set this logger at Info - we'll change it later but we need to start with something.
  474. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "info", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  475. var err error
  476. if AppPath, err = getAppPath(); err != nil {
  477. log.Fatal("Failed to get app path: %v", err)
  478. }
  479. AppWorkPath = getWorkPath(AppPath)
  480. }
  481. func forcePathSeparator(path string) {
  482. if strings.Contains(path, "\\") {
  483. log.Fatal("Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  484. }
  485. }
  486. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  487. // actual user that runs the app. The first return value is the actual user name.
  488. // This check is ignored under Windows since SSH remote login is not the main
  489. // method to login on Windows.
  490. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  491. if IsWindows || SSH.StartBuiltinServer {
  492. return "", true
  493. }
  494. currentUser := user.CurrentUsername()
  495. return currentUser, runUser == currentUser
  496. }
  497. func createPIDFile(pidPath string) {
  498. currentPid := os.Getpid()
  499. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  500. log.Fatal("Failed to create PID folder: %v", err)
  501. }
  502. file, err := os.Create(pidPath)
  503. if err != nil {
  504. log.Fatal("Failed to create PID file: %v", err)
  505. }
  506. defer file.Close()
  507. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  508. log.Fatal("Failed to write PID information: %v", err)
  509. }
  510. }
  511. // SetCustomPathAndConf will set CustomPath and CustomConf with reference to the
  512. // GITEA_CUSTOM environment variable and with provided overrides before stepping
  513. // back to the default
  514. func SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath string) {
  515. if len(providedWorkPath) != 0 {
  516. AppWorkPath = filepath.ToSlash(providedWorkPath)
  517. }
  518. if giteaCustom, ok := os.LookupEnv("GITEA_CUSTOM"); ok {
  519. CustomPath = giteaCustom
  520. }
  521. if len(providedCustom) != 0 {
  522. CustomPath = providedCustom
  523. }
  524. if len(CustomPath) == 0 {
  525. CustomPath = path.Join(AppWorkPath, "custom")
  526. } else if !filepath.IsAbs(CustomPath) {
  527. CustomPath = path.Join(AppWorkPath, CustomPath)
  528. }
  529. if len(providedConf) != 0 {
  530. CustomConf = providedConf
  531. }
  532. if len(CustomConf) == 0 {
  533. CustomConf = path.Join(CustomPath, "conf/app.ini")
  534. } else if !filepath.IsAbs(CustomConf) {
  535. CustomConf = path.Join(CustomPath, CustomConf)
  536. log.Warn("Using 'custom' directory as relative origin for configuration file: '%s'", CustomConf)
  537. }
  538. }
  539. // LoadFromExisting initializes setting options from an existing config file (app.ini)
  540. func LoadFromExisting() {
  541. loadFromConf(false, "")
  542. }
  543. // LoadAllowEmpty initializes setting options, it's also fine that if the config file (app.ini) doesn't exist
  544. func LoadAllowEmpty() {
  545. loadFromConf(true, "")
  546. }
  547. // LoadForTest initializes setting options for tests
  548. func LoadForTest(extraConfigs ...string) {
  549. loadFromConf(true, strings.Join(extraConfigs, "\n"))
  550. if err := PrepareAppDataPath(); err != nil {
  551. log.Fatal("Can not prepare APP_DATA_PATH: %v", err)
  552. }
  553. }
  554. func deprecatedSetting(oldSection, oldKey, newSection, newKey string) {
  555. if Cfg.Section(oldSection).HasKey(oldKey) {
  556. log.Error("Deprecated fallback `[%s]` `%s` present. Use `[%s]` `%s` instead. This fallback will be removed in v1.19.0", oldSection, oldKey, newSection, newKey)
  557. }
  558. }
  559. // deprecatedSettingDB add a hint that the configuration has been moved to database but still kept in app.ini
  560. func deprecatedSettingDB(oldSection, oldKey string) {
  561. if Cfg.Section(oldSection).HasKey(oldKey) {
  562. log.Error("Deprecated `[%s]` `%s` present which has been copied to database table sys_setting", oldSection, oldKey)
  563. }
  564. }
  565. // loadFromConf initializes configuration context.
  566. // NOTE: do not print any log except error.
  567. func loadFromConf(allowEmpty bool, extraConfig string) {
  568. Cfg = ini.Empty()
  569. if WritePIDFile && len(PIDFile) > 0 {
  570. createPIDFile(PIDFile)
  571. }
  572. isFile, err := util.IsFile(CustomConf)
  573. if err != nil {
  574. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  575. }
  576. if isFile {
  577. if err := Cfg.Append(CustomConf); err != nil {
  578. log.Fatal("Failed to load custom conf '%s': %v", CustomConf, err)
  579. }
  580. } else if !allowEmpty {
  581. log.Fatal("Unable to find configuration file: %q.\nEnsure you are running in the correct environment or set the correct configuration file with -c.", CustomConf)
  582. } // else: no config file, a config file might be created at CustomConf later (might not)
  583. if extraConfig != "" {
  584. if err = Cfg.Append([]byte(extraConfig)); err != nil {
  585. log.Fatal("Unable to append more config: %v", err)
  586. }
  587. }
  588. Cfg.NameMapper = ini.SnackCase
  589. homeDir, err := util.HomeDir()
  590. if err != nil {
  591. log.Fatal("Failed to get home directory: %v", err)
  592. }
  593. homeDir = strings.ReplaceAll(homeDir, "\\", "/")
  594. LogLevel = getLogLevel(Cfg.Section("log"), "LEVEL", log.INFO)
  595. StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None")
  596. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  597. forcePathSeparator(LogRootPath)
  598. sec := Cfg.Section("server")
  599. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  600. Domain = sec.Key("DOMAIN").MustString("localhost")
  601. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  602. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  603. Protocol = HTTP
  604. protocolCfg := sec.Key("PROTOCOL").String()
  605. switch protocolCfg {
  606. case "https":
  607. Protocol = HTTPS
  608. // FIXME: DEPRECATED to be removed in v1.18.0
  609. if sec.HasKey("ENABLE_ACME") {
  610. EnableAcme = sec.Key("ENABLE_ACME").MustBool(false)
  611. } else {
  612. deprecatedSetting("server", "ENABLE_LETSENCRYPT", "server", "ENABLE_ACME")
  613. EnableAcme = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  614. }
  615. if EnableAcme {
  616. AcmeURL = sec.Key("ACME_URL").MustString("")
  617. AcmeCARoot = sec.Key("ACME_CA_ROOT").MustString("")
  618. // FIXME: DEPRECATED to be removed in v1.18.0
  619. if sec.HasKey("ACME_ACCEPTTOS") {
  620. AcmeTOS = sec.Key("ACME_ACCEPTTOS").MustBool(false)
  621. } else {
  622. deprecatedSetting("server", "LETSENCRYPT_ACCEPTTOS", "server", "ACME_ACCEPTTOS")
  623. AcmeTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  624. }
  625. if !AcmeTOS {
  626. log.Fatal("ACME TOS is not accepted (ACME_ACCEPTTOS).")
  627. }
  628. // FIXME: DEPRECATED to be removed in v1.18.0
  629. if sec.HasKey("ACME_DIRECTORY") {
  630. AcmeLiveDirectory = sec.Key("ACME_DIRECTORY").MustString("https")
  631. } else {
  632. deprecatedSetting("server", "LETSENCRYPT_DIRECTORY", "server", "ACME_DIRECTORY")
  633. AcmeLiveDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  634. }
  635. // FIXME: DEPRECATED to be removed in v1.18.0
  636. if sec.HasKey("ACME_EMAIL") {
  637. AcmeEmail = sec.Key("ACME_EMAIL").MustString("")
  638. } else {
  639. deprecatedSetting("server", "LETSENCRYPT_EMAIL", "server", "ACME_EMAIL")
  640. AcmeEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  641. }
  642. } else {
  643. CertFile = sec.Key("CERT_FILE").String()
  644. KeyFile = sec.Key("KEY_FILE").String()
  645. if len(CertFile) > 0 && !filepath.IsAbs(CertFile) {
  646. CertFile = filepath.Join(CustomPath, CertFile)
  647. }
  648. if len(KeyFile) > 0 && !filepath.IsAbs(KeyFile) {
  649. KeyFile = filepath.Join(CustomPath, KeyFile)
  650. }
  651. }
  652. SSLMinimumVersion = sec.Key("SSL_MIN_VERSION").MustString("")
  653. SSLMaximumVersion = sec.Key("SSL_MAX_VERSION").MustString("")
  654. SSLCurvePreferences = sec.Key("SSL_CURVE_PREFERENCES").Strings(",")
  655. SSLCipherSuites = sec.Key("SSL_CIPHER_SUITES").Strings(",")
  656. case "fcgi":
  657. Protocol = FCGI
  658. case "fcgi+unix", "unix", "http+unix":
  659. switch protocolCfg {
  660. case "fcgi+unix":
  661. Protocol = FCGIUnix
  662. case "unix":
  663. log.Warn("unix PROTOCOL value is deprecated, please use http+unix")
  664. fallthrough
  665. case "http+unix":
  666. Protocol = HTTPUnix
  667. }
  668. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  669. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  670. if err != nil || UnixSocketPermissionParsed > 0o777 {
  671. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  672. }
  673. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  674. if !filepath.IsAbs(HTTPAddr) {
  675. HTTPAddr = filepath.Join(AppWorkPath, HTTPAddr)
  676. }
  677. }
  678. UseProxyProtocol = sec.Key("USE_PROXY_PROTOCOL").MustBool(false)
  679. ProxyProtocolTLSBridging = sec.Key("PROXY_PROTOCOL_TLS_BRIDGING").MustBool(false)
  680. ProxyProtocolHeaderTimeout = sec.Key("PROXY_PROTOCOL_HEADER_TIMEOUT").MustDuration(5 * time.Second)
  681. ProxyProtocolAcceptUnknown = sec.Key("PROXY_PROTOCOL_ACCEPT_UNKNOWN").MustBool(false)
  682. GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
  683. GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
  684. StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)
  685. PerWriteTimeout = sec.Key("PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  686. PerWritePerKbTimeout = sec.Key("PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  687. defaultAppURL := string(Protocol) + "://" + Domain
  688. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  689. defaultAppURL += ":" + HTTPPort
  690. }
  691. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL + "/")
  692. // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL.
  693. AppURL = strings.TrimRight(AppURL, "/") + "/"
  694. // Check if has app suburl.
  695. appURL, err := url.Parse(AppURL)
  696. if err != nil {
  697. log.Fatal("Invalid ROOT_URL '%s': %s", AppURL, err)
  698. }
  699. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  700. // This value is empty if site does not have sub-url.
  701. AppSubURL = strings.TrimSuffix(appURL.Path, "/")
  702. StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/")
  703. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  704. urlHostname := appURL.Hostname()
  705. if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" {
  706. Domain = urlHostname
  707. }
  708. AbsoluteAssetURL = MakeAbsoluteAssetURL(AppURL, StaticURLPrefix)
  709. AssetVersion = strings.ReplaceAll(AppVer, "+", "~") // make sure the version string is clear (no real escaping is needed)
  710. manifestBytes := MakeManifestData(AppName, AppURL, AbsoluteAssetURL)
  711. ManifestData = `application/json;base64,` + base64.StdEncoding.EncodeToString(manifestBytes)
  712. var defaultLocalURL string
  713. switch Protocol {
  714. case HTTPUnix:
  715. defaultLocalURL = "http://unix/"
  716. case FCGI:
  717. defaultLocalURL = AppURL
  718. case FCGIUnix:
  719. defaultLocalURL = AppURL
  720. default:
  721. defaultLocalURL = string(Protocol) + "://"
  722. if HTTPAddr == "0.0.0.0" {
  723. defaultLocalURL += net.JoinHostPort("localhost", HTTPPort) + "/"
  724. } else {
  725. defaultLocalURL += net.JoinHostPort(HTTPAddr, HTTPPort) + "/"
  726. }
  727. }
  728. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  729. LocalURL = strings.TrimRight(LocalURL, "/") + "/"
  730. LocalUseProxyProtocol = sec.Key("LOCAL_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol)
  731. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  732. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  733. RedirectorUseProxyProtocol = sec.Key("REDIRECTOR_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol)
  734. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  735. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  736. if len(StaticRootPath) == 0 {
  737. StaticRootPath = AppWorkPath
  738. }
  739. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(StaticRootPath)
  740. StaticCacheTime = sec.Key("STATIC_CACHE_TIME").MustDuration(6 * time.Hour)
  741. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  742. if !filepath.IsAbs(AppDataPath) {
  743. log.Info("The provided APP_DATA_PATH: %s is not absolute - it will be made absolute against the work path: %s", AppDataPath, AppWorkPath)
  744. AppDataPath = filepath.ToSlash(filepath.Join(AppWorkPath, AppDataPath))
  745. }
  746. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  747. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  748. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  749. if !filepath.IsAbs(PprofDataPath) {
  750. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  751. }
  752. landingPage := sec.Key("LANDING_PAGE").MustString("home")
  753. switch landingPage {
  754. case "explore":
  755. LandingPageURL = LandingPageExplore
  756. case "organizations":
  757. LandingPageURL = LandingPageOrganizations
  758. case "login":
  759. LandingPageURL = LandingPageLogin
  760. case "":
  761. case "home":
  762. LandingPageURL = LandingPageHome
  763. default:
  764. LandingPageURL = LandingPage(landingPage)
  765. }
  766. if len(SSH.Domain) == 0 {
  767. SSH.Domain = Domain
  768. }
  769. SSH.RootPath = path.Join(homeDir, ".ssh")
  770. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  771. if len(serverCiphers) > 0 {
  772. SSH.ServerCiphers = serverCiphers
  773. }
  774. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  775. if len(serverKeyExchanges) > 0 {
  776. SSH.ServerKeyExchanges = serverKeyExchanges
  777. }
  778. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  779. if len(serverMACs) > 0 {
  780. SSH.ServerMACs = serverMACs
  781. }
  782. SSH.KeyTestPath = os.TempDir()
  783. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  784. log.Fatal("Failed to map SSH settings: %v", err)
  785. }
  786. for i, key := range SSH.ServerHostKeys {
  787. if !filepath.IsAbs(key) {
  788. SSH.ServerHostKeys[i] = filepath.Join(AppDataPath, key)
  789. }
  790. }
  791. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  792. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  793. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  794. SSH.UseProxyProtocol = sec.Key("SSH_SERVER_USE_PROXY_PROTOCOL").MustBool(false)
  795. // When disable SSH, start builtin server value is ignored.
  796. if SSH.Disabled {
  797. SSH.StartBuiltinServer = false
  798. }
  799. SSH.TrustedUserCAKeysFile = sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem"))
  800. for _, caKey := range SSH.TrustedUserCAKeys {
  801. pubKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(caKey))
  802. if err != nil {
  803. log.Fatal("Failed to parse TrustedUserCaKeys: %s %v", caKey, err)
  804. }
  805. SSH.TrustedUserCAKeysParsed = append(SSH.TrustedUserCAKeysParsed, pubKey)
  806. }
  807. if len(SSH.TrustedUserCAKeys) > 0 {
  808. // Set the default as email,username otherwise we can leave it empty
  809. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("username,email")
  810. } else {
  811. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("off")
  812. }
  813. SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(","))
  814. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool(SSH.MinimumKeySizeCheck)
  815. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  816. for _, key := range minimumKeySizes {
  817. if key.MustInt() != -1 {
  818. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  819. } else {
  820. delete(SSH.MinimumKeySizes, strings.ToLower(key.Name()))
  821. }
  822. }
  823. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  824. SSH.CreateAuthorizedKeysFile = sec.Key("SSH_CREATE_AUTHORIZED_KEYS_FILE").MustBool(true)
  825. SSH.AuthorizedPrincipalsBackup = false
  826. SSH.CreateAuthorizedPrincipalsFile = false
  827. if SSH.AuthorizedPrincipalsEnabled {
  828. SSH.AuthorizedPrincipalsBackup = sec.Key("SSH_AUTHORIZED_PRINCIPALS_BACKUP").MustBool(true)
  829. SSH.CreateAuthorizedPrincipalsFile = sec.Key("SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE").MustBool(true)
  830. }
  831. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  832. SSH.AuthorizedKeysCommandTemplate = sec.Key("SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE").MustString(SSH.AuthorizedKeysCommandTemplate)
  833. SSH.AuthorizedKeysCommandTemplateTemplate = template.Must(template.New("").Parse(SSH.AuthorizedKeysCommandTemplate))
  834. SSH.PerWriteTimeout = sec.Key("SSH_PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  835. SSH.PerWritePerKbTimeout = sec.Key("SSH_PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  836. if err = Cfg.Section("oauth2").MapTo(&OAuth2); err != nil {
  837. log.Fatal("Failed to OAuth2 settings: %v", err)
  838. return
  839. }
  840. if !filepath.IsAbs(OAuth2.JWTSigningPrivateKeyFile) {
  841. OAuth2.JWTSigningPrivateKeyFile = filepath.Join(AppDataPath, OAuth2.JWTSigningPrivateKeyFile)
  842. }
  843. sec = Cfg.Section("admin")
  844. Admin.DefaultEmailNotification = sec.Key("DEFAULT_EMAIL_NOTIFICATIONS").MustString("enabled")
  845. sec = Cfg.Section("security")
  846. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  847. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  848. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  849. SecretKey = loadSecret(sec, "SECRET_KEY_URI", "SECRET_KEY")
  850. if SecretKey == "" {
  851. // FIXME: https://github.com/go-gitea/gitea/issues/16832
  852. // Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value
  853. SecretKey = "!#@FDEWREWR&*(" // nolint:gosec
  854. }
  855. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  856. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  857. ReverseProxyAuthEmail = sec.Key("REVERSE_PROXY_AUTHENTICATION_EMAIL").MustString("X-WEBAUTH-EMAIL")
  858. ReverseProxyAuthFullName = sec.Key("REVERSE_PROXY_AUTHENTICATION_FULL_NAME").MustString("X-WEBAUTH-FULLNAME")
  859. ReverseProxyLimit = sec.Key("REVERSE_PROXY_LIMIT").MustInt(1)
  860. ReverseProxyTrustedProxies = sec.Key("REVERSE_PROXY_TRUSTED_PROXIES").Strings(",")
  861. if len(ReverseProxyTrustedProxies) == 0 {
  862. ReverseProxyTrustedProxies = []string{"127.0.0.0/8", "::1/128"}
  863. }
  864. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  865. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  866. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(true)
  867. DisableWebhooks = sec.Key("DISABLE_WEBHOOKS").MustBool(false)
  868. OnlyAllowPushIfGiteaEnvironmentSet = sec.Key("ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET").MustBool(true)
  869. PasswordHashAlgo = sec.Key("PASSWORD_HASH_ALGO").MustString("pbkdf2")
  870. CSRFCookieHTTPOnly = sec.Key("CSRF_COOKIE_HTTP_ONLY").MustBool(true)
  871. PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
  872. SuccessfulTokensCacheSize = sec.Key("SUCCESSFUL_TOKENS_CACHE_SIZE").MustInt(20)
  873. InternalToken = loadSecret(sec, "INTERNAL_TOKEN_URI", "INTERNAL_TOKEN")
  874. if InstallLock && InternalToken == "" {
  875. // if Gitea has been installed but the InternalToken hasn't been generated (upgrade from an old release), we should generate
  876. // some users do cluster deployment, they still depend on this auto-generating behavior.
  877. generateSaveInternalToken()
  878. }
  879. cfgdata := sec.Key("PASSWORD_COMPLEXITY").Strings(",")
  880. if len(cfgdata) == 0 {
  881. cfgdata = []string{"off"}
  882. }
  883. PasswordComplexity = make([]string, 0, len(cfgdata))
  884. for _, name := range cfgdata {
  885. name := strings.ToLower(strings.Trim(name, `"`))
  886. if name != "" {
  887. PasswordComplexity = append(PasswordComplexity, name)
  888. }
  889. }
  890. newAttachmentService()
  891. newLFSService()
  892. timeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("")
  893. if timeFormatKey != "" {
  894. TimeFormat = map[string]string{
  895. "ANSIC": time.ANSIC,
  896. "UnixDate": time.UnixDate,
  897. "RubyDate": time.RubyDate,
  898. "RFC822": time.RFC822,
  899. "RFC822Z": time.RFC822Z,
  900. "RFC850": time.RFC850,
  901. "RFC1123": time.RFC1123,
  902. "RFC1123Z": time.RFC1123Z,
  903. "RFC3339": time.RFC3339,
  904. "RFC3339Nano": time.RFC3339Nano,
  905. "Kitchen": time.Kitchen,
  906. "Stamp": time.Stamp,
  907. "StampMilli": time.StampMilli,
  908. "StampMicro": time.StampMicro,
  909. "StampNano": time.StampNano,
  910. }[timeFormatKey]
  911. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  912. if len(TimeFormat) == 0 {
  913. TimeFormat = timeFormatKey
  914. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  915. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  916. log.Warn("Provided TimeFormat: %s does not create a fully specified date and time.", TimeFormat)
  917. log.Warn("In order to display dates and times correctly please check your time format has 2006, 01, 02, 15, 04 and 05")
  918. }
  919. log.Trace("Custom TimeFormat: %s", TimeFormat)
  920. }
  921. }
  922. zone := Cfg.Section("time").Key("DEFAULT_UI_LOCATION").String()
  923. if zone != "" {
  924. DefaultUILocation, err = time.LoadLocation(zone)
  925. if err != nil {
  926. log.Fatal("Load time zone failed: %v", err)
  927. } else {
  928. log.Info("Default UI Location is %v", zone)
  929. }
  930. }
  931. if DefaultUILocation == nil {
  932. DefaultUILocation = time.Local
  933. }
  934. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  935. // The following is a purposefully undocumented option. Please do not run Gitea as root. It will only cause future headaches.
  936. // Please don't use root as a bandaid to "fix" something that is broken, instead the broken thing should instead be fixed properly.
  937. unsafeAllowRunAsRoot := Cfg.Section("").Key("I_AM_BEING_UNSAFE_RUNNING_AS_ROOT").MustBool(false)
  938. RunMode = Cfg.Section("").Key("RUN_MODE").MustString("prod")
  939. IsProd = strings.EqualFold(RunMode, "prod")
  940. // Does not check run user when the install lock is off.
  941. if InstallLock {
  942. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  943. if !match {
  944. log.Fatal("Expect user '%s' but current user is: %s", RunUser, currentUser)
  945. }
  946. }
  947. // check if we run as root
  948. if os.Getuid() == 0 {
  949. if !unsafeAllowRunAsRoot {
  950. // Special thanks to VLC which inspired the wording of this messaging.
  951. log.Fatal("Gitea is not supposed to be run as root. Sorry. If you need to use privileged TCP ports please instead use setcap and the `cap_net_bind_service` permission")
  952. }
  953. log.Critical("You are running Gitea using the root user, and have purposely chosen to skip built-in protections around this. You have been warned against this.")
  954. }
  955. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  956. SSH.User = Cfg.Section("server").Key("SSH_USER").MustString(SSH.BuiltinServerUser)
  957. newRepository()
  958. newPictureService()
  959. newPackages()
  960. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  961. log.Fatal("Failed to map UI settings: %v", err)
  962. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  963. log.Fatal("Failed to map Markdown settings: %v", err)
  964. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  965. log.Fatal("Fail to map Admin settings: %v", err)
  966. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  967. log.Fatal("Failed to map API settings: %v", err)
  968. } else if err = Cfg.Section("metrics").MapTo(&Metrics); err != nil {
  969. log.Fatal("Failed to map Metrics settings: %v", err)
  970. } else if err = Cfg.Section("camo").MapTo(&Camo); err != nil {
  971. log.Fatal("Failed to map Camo settings: %v", err)
  972. }
  973. if Camo.Enabled {
  974. if Camo.ServerURL == "" || Camo.HMACKey == "" {
  975. log.Fatal(`Camo settings require "SERVER_URL" and HMAC_KEY`)
  976. }
  977. }
  978. u := *appURL
  979. u.Path = path.Join(u.Path, "api", "swagger")
  980. API.SwaggerURL = u.String()
  981. newGit()
  982. newMirror()
  983. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  984. if len(Langs) == 0 {
  985. Langs = defaultI18nLangs()
  986. }
  987. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  988. if len(Names) == 0 {
  989. Names = defaultI18nNames()
  990. }
  991. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  992. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  993. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  994. EnableSitemap = Cfg.Section("other").Key("ENABLE_SITEMAP").MustBool(true)
  995. EnableFeed = Cfg.Section("other").Key("ENABLE_FEED").MustBool(true)
  996. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  997. UI.DefaultShowFullName = Cfg.Section("ui").Key("DEFAULT_SHOW_FULL_NAME").MustBool(false)
  998. UI.SearchRepoDescription = Cfg.Section("ui").Key("SEARCH_REPO_DESCRIPTION").MustBool(true)
  999. UI.UseServiceWorker = Cfg.Section("ui").Key("USE_SERVICE_WORKER").MustBool(false)
  1000. UI.OnlyShowRelevantRepos = Cfg.Section("ui").Key("ONLY_SHOW_RELEVANT_REPOS").MustBool(false)
  1001. HasRobotsTxt, err = util.IsFile(path.Join(CustomPath, "robots.txt"))
  1002. if err != nil {
  1003. log.Error("Unable to check if %s is a file. Error: %v", path.Join(CustomPath, "robots.txt"), err)
  1004. }
  1005. newMarkup()
  1006. UI.ReactionsLookup = make(container.Set[string])
  1007. for _, reaction := range UI.Reactions {
  1008. UI.ReactionsLookup.Add(reaction)
  1009. }
  1010. UI.CustomEmojisMap = make(map[string]string)
  1011. for _, emoji := range UI.CustomEmojis {
  1012. UI.CustomEmojisMap[emoji] = ":" + emoji + ":"
  1013. }
  1014. }
  1015. func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) {
  1016. anything := false
  1017. email := false
  1018. username := false
  1019. for _, value := range values {
  1020. v := strings.ToLower(strings.TrimSpace(value))
  1021. switch v {
  1022. case "off":
  1023. return []string{"off"}, false
  1024. case "email":
  1025. email = true
  1026. case "username":
  1027. username = true
  1028. case "anything":
  1029. anything = true
  1030. }
  1031. }
  1032. if anything {
  1033. return []string{"anything"}, true
  1034. }
  1035. authorizedPrincipalsAllow := []string{}
  1036. if username {
  1037. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "username")
  1038. }
  1039. if email {
  1040. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "email")
  1041. }
  1042. return authorizedPrincipalsAllow, true
  1043. }
  1044. // loadSecret load the secret from ini by uriKey or verbatimKey, only one of them could be set
  1045. // If the secret is loaded from uriKey (file), the file should be non-empty, to guarantee the behavior stable and clear.
  1046. func loadSecret(sec *ini.Section, uriKey, verbatimKey string) string {
  1047. // don't allow setting both URI and verbatim string
  1048. uri := sec.Key(uriKey).String()
  1049. verbatim := sec.Key(verbatimKey).String()
  1050. if uri != "" && verbatim != "" {
  1051. log.Fatal("Cannot specify both %s and %s", uriKey, verbatimKey)
  1052. }
  1053. // if we have no URI, use verbatim
  1054. if uri == "" {
  1055. return verbatim
  1056. }
  1057. tempURI, err := url.Parse(uri)
  1058. if err != nil {
  1059. log.Fatal("Failed to parse %s (%s): %v", uriKey, uri, err)
  1060. }
  1061. switch tempURI.Scheme {
  1062. case "file":
  1063. buf, err := os.ReadFile(tempURI.RequestURI())
  1064. if err != nil {
  1065. log.Fatal("Failed to read %s (%s): %v", uriKey, tempURI.RequestURI(), err)
  1066. }
  1067. val := strings.TrimSpace(string(buf))
  1068. if val == "" {
  1069. // The file shouldn't be empty, otherwise we can not know whether the user has ever set the KEY or KEY_URI
  1070. // For example: if INTERNAL_TOKEN_URI=file:///empty-file,
  1071. // Then if the token is re-generated during installation and saved to INTERNAL_TOKEN
  1072. // Then INTERNAL_TOKEN and INTERNAL_TOKEN_URI both exist, that's a fatal error (they shouldn't)
  1073. log.Fatal("Failed to read %s (%s): the file is empty", uriKey, tempURI.RequestURI())
  1074. }
  1075. return val
  1076. // only file URIs are allowed
  1077. default:
  1078. log.Fatal("Unsupported URI-Scheme %q (INTERNAL_TOKEN_URI = %q)", tempURI.Scheme, uri)
  1079. return ""
  1080. }
  1081. }
  1082. // generateSaveInternalToken generates and saves the internal token to app.ini
  1083. func generateSaveInternalToken() {
  1084. token, err := generate.NewInternalToken()
  1085. if err != nil {
  1086. log.Fatal("Error generate internal token: %v", err)
  1087. }
  1088. InternalToken = token
  1089. CreateOrAppendToCustomConf("security.INTERNAL_TOKEN", func(cfg *ini.File) {
  1090. cfg.Section("security").Key("INTERNAL_TOKEN").SetValue(token)
  1091. })
  1092. }
  1093. // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
  1094. func MakeAbsoluteAssetURL(appURL, staticURLPrefix string) string {
  1095. parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/"))
  1096. if err != nil {
  1097. log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err)
  1098. }
  1099. if err == nil && parsedPrefix.Hostname() == "" {
  1100. if staticURLPrefix == "" {
  1101. return strings.TrimSuffix(appURL, "/")
  1102. }
  1103. // StaticURLPrefix is just a path
  1104. return util.URLJoin(appURL, strings.TrimSuffix(staticURLPrefix, "/"))
  1105. }
  1106. return strings.TrimSuffix(staticURLPrefix, "/")
  1107. }
  1108. // MakeManifestData generates web app manifest JSON
  1109. func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {
  1110. type manifestIcon struct {
  1111. Src string `json:"src"`
  1112. Type string `json:"type"`
  1113. Sizes string `json:"sizes"`
  1114. }
  1115. type manifestJSON struct {
  1116. Name string `json:"name"`
  1117. ShortName string `json:"short_name"`
  1118. StartURL string `json:"start_url"`
  1119. Icons []manifestIcon `json:"icons"`
  1120. }
  1121. bytes, err := json.Marshal(&manifestJSON{
  1122. Name: appName,
  1123. ShortName: appName,
  1124. StartURL: appURL,
  1125. Icons: []manifestIcon{
  1126. {
  1127. Src: absoluteAssetURL + "/assets/img/logo.png",
  1128. Type: "image/png",
  1129. Sizes: "512x512",
  1130. },
  1131. {
  1132. Src: absoluteAssetURL + "/assets/img/logo.svg",
  1133. Type: "image/svg+xml",
  1134. Sizes: "512x512",
  1135. },
  1136. },
  1137. })
  1138. if err != nil {
  1139. log.Error("unable to marshal manifest JSON. Error: %v", err)
  1140. return make([]byte, 0)
  1141. }
  1142. return bytes
  1143. }
  1144. // CreateOrAppendToCustomConf creates or updates the custom config.
  1145. // Use the callback to set individual values.
  1146. func CreateOrAppendToCustomConf(purpose string, callback func(cfg *ini.File)) {
  1147. if CustomConf == "" {
  1148. log.Error("Custom config path must not be empty")
  1149. return
  1150. }
  1151. cfg := ini.Empty()
  1152. isFile, err := util.IsFile(CustomConf)
  1153. if err != nil {
  1154. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  1155. }
  1156. if isFile {
  1157. if err := cfg.Append(CustomConf); err != nil {
  1158. log.Error("failed to load custom conf %s: %v", CustomConf, err)
  1159. return
  1160. }
  1161. }
  1162. callback(cfg)
  1163. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  1164. log.Fatal("failed to create '%s': %v", CustomConf, err)
  1165. return
  1166. }
  1167. if err := cfg.SaveTo(CustomConf); err != nil {
  1168. log.Fatal("error saving to custom config: %v", err)
  1169. }
  1170. log.Info("Settings for %s saved to: %q", purpose, CustomConf)
  1171. // Change permissions to be more restrictive
  1172. fi, err := os.Stat(CustomConf)
  1173. if err != nil {
  1174. log.Error("Failed to determine current conf file permissions: %v", err)
  1175. return
  1176. }
  1177. if fi.Mode().Perm() > 0o600 {
  1178. if err = os.Chmod(CustomConf, 0o600); err != nil {
  1179. log.Warn("Failed changing conf file permissions to -rw-------. Consider changing them manually.")
  1180. }
  1181. }
  1182. }
  1183. // NewServices initializes the services
  1184. func NewServices() {
  1185. InitDBConfig()
  1186. newService()
  1187. newOAuth2Client()
  1188. NewLogServices(false)
  1189. newCacheService()
  1190. newSessionService()
  1191. newCORSService()
  1192. newMailService()
  1193. newRegisterMailService()
  1194. newNotifyMailService()
  1195. newProxyService()
  1196. newWebhookService()
  1197. newMigrationsService()
  1198. newIndexerService()
  1199. newTaskService()
  1200. NewQueueService()
  1201. newProject()
  1202. newMimeTypeMap()
  1203. newFederationService()
  1204. }
  1205. // NewServicesForInstall initializes the services for install
  1206. func NewServicesForInstall() {
  1207. newService()
  1208. newMailService()
  1209. }