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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. "io"
  10. "io/ioutil"
  11. "math"
  12. "net"
  13. "net/url"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/user"
  25. "code.gitea.io/gitea/modules/util"
  26. jsoniter "github.com/json-iterator/go"
  27. shellquote "github.com/kballard/go-shellquote"
  28. "github.com/unknwon/com"
  29. gossh "golang.org/x/crypto/ssh"
  30. ini "gopkg.in/ini.v1"
  31. )
  32. // Scheme describes protocol types
  33. type Scheme string
  34. // enumerates all the scheme types
  35. const (
  36. HTTP Scheme = "http"
  37. HTTPS Scheme = "https"
  38. FCGI Scheme = "fcgi"
  39. FCGIUnix Scheme = "fcgi+unix"
  40. UnixSocket Scheme = "unix"
  41. )
  42. // LandingPage describes the default page
  43. type LandingPage string
  44. // enumerates all the landing page types
  45. const (
  46. LandingPageHome LandingPage = "/"
  47. LandingPageExplore LandingPage = "/explore"
  48. LandingPageOrganizations LandingPage = "/explore/organizations"
  49. LandingPageLogin LandingPage = "/user/login"
  50. )
  51. // enumerates all the types of captchas
  52. const (
  53. ImageCaptcha = "image"
  54. ReCaptcha = "recaptcha"
  55. HCaptcha = "hcaptcha"
  56. )
  57. // settings
  58. var (
  59. // AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
  60. AppVer string
  61. // AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
  62. AppBuiltWith string
  63. // AppStartTime store time gitea has started
  64. AppStartTime time.Time
  65. // AppName is the Application name, used in the page title.
  66. // It maps to ini:"APP_NAME"
  67. AppName string
  68. // AppURL is the Application ROOT_URL. It always has a '/' suffix
  69. // It maps to ini:"ROOT_URL"
  70. AppURL string
  71. // AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
  72. // This value is empty if site does not have sub-url.
  73. AppSubURL string
  74. // AppPath represents the path to the gitea binary
  75. AppPath string
  76. // AppWorkPath is the "working directory" of Gitea. It maps to the environment variable GITEA_WORK_DIR.
  77. // If that is not set it is the default set here by the linker or failing that the directory of AppPath.
  78. //
  79. // AppWorkPath is used as the base path for several other paths.
  80. AppWorkPath string
  81. // AppDataPath is the default path for storing data.
  82. // It maps to ini:"APP_DATA_PATH" and defaults to AppWorkPath + "/data"
  83. AppDataPath string
  84. // Server settings
  85. Protocol Scheme
  86. Domain string
  87. HTTPAddr string
  88. HTTPPort string
  89. LocalURL string
  90. RedirectOtherPort bool
  91. PortToRedirect string
  92. OfflineMode bool
  93. CertFile string
  94. KeyFile string
  95. StaticRootPath string
  96. StaticCacheTime time.Duration
  97. EnableGzip bool
  98. LandingPageURL LandingPage
  99. UnixSocketPermission uint32
  100. EnablePprof bool
  101. PprofDataPath string
  102. EnableLetsEncrypt bool
  103. LetsEncryptTOS bool
  104. LetsEncryptDirectory string
  105. LetsEncryptEmail string
  106. GracefulRestartable bool
  107. GracefulHammerTime time.Duration
  108. StartupTimeout time.Duration
  109. StaticURLPrefix string
  110. AbsoluteAssetURL string
  111. SSH = struct {
  112. Disabled bool `ini:"DISABLE_SSH"`
  113. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  114. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  115. Domain string `ini:"SSH_DOMAIN"`
  116. Port int `ini:"SSH_PORT"`
  117. ListenHost string `ini:"SSH_LISTEN_HOST"`
  118. ListenPort int `ini:"SSH_LISTEN_PORT"`
  119. RootPath string `ini:"SSH_ROOT_PATH"`
  120. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  121. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  122. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  123. ServerHostKeys []string `ini:"SSH_SERVER_HOST_KEYS"`
  124. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  125. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  126. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  127. AuthorizedPrincipalsBackup bool `ini:"SSH_AUTHORIZED_PRINCIPALS_BACKUP"`
  128. MinimumKeySizeCheck bool `ini:"-"`
  129. MinimumKeySizes map[string]int `ini:"-"`
  130. CreateAuthorizedKeysFile bool `ini:"SSH_CREATE_AUTHORIZED_KEYS_FILE"`
  131. CreateAuthorizedPrincipalsFile bool `ini:"SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE"`
  132. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  133. AuthorizedPrincipalsAllow []string `ini:"SSH_AUTHORIZED_PRINCIPALS_ALLOW"`
  134. AuthorizedPrincipalsEnabled bool `ini:"-"`
  135. TrustedUserCAKeys []string `ini:"SSH_TRUSTED_USER_CA_KEYS"`
  136. TrustedUserCAKeysFile string `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
  137. TrustedUserCAKeysParsed []gossh.PublicKey `ini:"-"`
  138. }{
  139. Disabled: false,
  140. StartBuiltinServer: false,
  141. Domain: "",
  142. Port: 22,
  143. ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128"},
  144. ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "curve25519-sha256@libssh.org"},
  145. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
  146. KeygenPath: "ssh-keygen",
  147. MinimumKeySizeCheck: true,
  148. MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2048},
  149. ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
  150. }
  151. // Security settings
  152. InstallLock bool
  153. SecretKey string
  154. LogInRememberDays int
  155. CookieUserName string
  156. CookieRememberName string
  157. ReverseProxyAuthUser string
  158. ReverseProxyAuthEmail string
  159. ReverseProxyLimit int
  160. ReverseProxyTrustedProxies []string
  161. MinPasswordLength int
  162. ImportLocalPaths bool
  163. DisableGitHooks bool
  164. DisableWebhooks bool
  165. OnlyAllowPushIfGiteaEnvironmentSet bool
  166. PasswordComplexity []string
  167. PasswordHashAlgo string
  168. PasswordCheckPwn bool
  169. // UI settings
  170. UI = struct {
  171. ExplorePagingNum int
  172. IssuePagingNum int
  173. RepoSearchPagingNum int
  174. MembersPagingNum int
  175. FeedMaxCommitNum int
  176. FeedPagingNum int
  177. GraphMaxCommitNum int
  178. CodeCommentLines int
  179. ReactionMaxUserNum int
  180. ThemeColorMetaTag string
  181. MaxDisplayFileSize int64
  182. ShowUserEmail bool
  183. DefaultShowFullName bool
  184. DefaultTheme string
  185. Themes []string
  186. Reactions []string
  187. ReactionsMap map[string]bool
  188. SearchRepoDescription bool
  189. UseServiceWorker bool
  190. Notification struct {
  191. MinTimeout time.Duration
  192. TimeoutStep time.Duration
  193. MaxTimeout time.Duration
  194. EventSourceUpdateTime time.Duration
  195. } `ini:"ui.notification"`
  196. SVG struct {
  197. Enabled bool `ini:"ENABLE_RENDER"`
  198. } `ini:"ui.svg"`
  199. CSV struct {
  200. MaxFileSize int64
  201. } `ini:"ui.csv"`
  202. Admin struct {
  203. UserPagingNum int
  204. RepoPagingNum int
  205. NoticePagingNum int
  206. OrgPagingNum int
  207. } `ini:"ui.admin"`
  208. User struct {
  209. RepoPagingNum int
  210. } `ini:"ui.user"`
  211. Meta struct {
  212. Author string
  213. Description string
  214. Keywords string
  215. } `ini:"ui.meta"`
  216. }{
  217. ExplorePagingNum: 20,
  218. IssuePagingNum: 10,
  219. RepoSearchPagingNum: 10,
  220. MembersPagingNum: 20,
  221. FeedMaxCommitNum: 5,
  222. FeedPagingNum: 20,
  223. GraphMaxCommitNum: 100,
  224. CodeCommentLines: 4,
  225. ReactionMaxUserNum: 10,
  226. ThemeColorMetaTag: `#6cc644`,
  227. MaxDisplayFileSize: 8388608,
  228. DefaultTheme: `gitea`,
  229. Themes: []string{`gitea`, `arc-green`},
  230. Reactions: []string{`+1`, `-1`, `laugh`, `hooray`, `confused`, `heart`, `rocket`, `eyes`},
  231. Notification: struct {
  232. MinTimeout time.Duration
  233. TimeoutStep time.Duration
  234. MaxTimeout time.Duration
  235. EventSourceUpdateTime time.Duration
  236. }{
  237. MinTimeout: 10 * time.Second,
  238. TimeoutStep: 10 * time.Second,
  239. MaxTimeout: 60 * time.Second,
  240. EventSourceUpdateTime: 10 * time.Second,
  241. },
  242. SVG: struct {
  243. Enabled bool `ini:"ENABLE_RENDER"`
  244. }{
  245. Enabled: true,
  246. },
  247. CSV: struct {
  248. MaxFileSize int64
  249. }{
  250. MaxFileSize: 524288,
  251. },
  252. Admin: struct {
  253. UserPagingNum int
  254. RepoPagingNum int
  255. NoticePagingNum int
  256. OrgPagingNum int
  257. }{
  258. UserPagingNum: 50,
  259. RepoPagingNum: 50,
  260. NoticePagingNum: 25,
  261. OrgPagingNum: 50,
  262. },
  263. User: struct {
  264. RepoPagingNum int
  265. }{
  266. RepoPagingNum: 15,
  267. },
  268. Meta: struct {
  269. Author string
  270. Description string
  271. Keywords string
  272. }{
  273. Author: "Gitea - Git with a cup of tea",
  274. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  275. Keywords: "go,git,self-hosted,gitea",
  276. },
  277. }
  278. // Markdown settings
  279. Markdown = struct {
  280. EnableHardLineBreakInComments bool
  281. EnableHardLineBreakInDocuments bool
  282. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  283. FileExtensions []string
  284. }{
  285. EnableHardLineBreakInComments: true,
  286. EnableHardLineBreakInDocuments: false,
  287. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  288. }
  289. // Admin settings
  290. Admin struct {
  291. DisableRegularOrgCreation bool
  292. DefaultEmailNotification string
  293. }
  294. // Log settings
  295. LogLevel log.Level
  296. StacktraceLogLevel string
  297. LogRootPath string
  298. DisableRouterLog bool
  299. RouterLogLevel log.Level
  300. EnableAccessLog bool
  301. AccessLogTemplate string
  302. EnableXORMLog bool
  303. // Time settings
  304. TimeFormat string
  305. // UILocation is the location on the UI, so that we can display the time on UI.
  306. DefaultUILocation = time.Local
  307. CSRFCookieName = "_csrf"
  308. CSRFCookieHTTPOnly = true
  309. ManifestData string
  310. // Mirror settings
  311. Mirror struct {
  312. DefaultInterval time.Duration
  313. MinInterval time.Duration
  314. }
  315. // API settings
  316. API = struct {
  317. EnableSwagger bool
  318. SwaggerURL string
  319. MaxResponseItems int
  320. DefaultPagingNum int
  321. DefaultGitTreesPerPage int
  322. DefaultMaxBlobSize int64
  323. }{
  324. EnableSwagger: true,
  325. SwaggerURL: "",
  326. MaxResponseItems: 50,
  327. DefaultPagingNum: 30,
  328. DefaultGitTreesPerPage: 1000,
  329. DefaultMaxBlobSize: 10485760,
  330. }
  331. OAuth2 = struct {
  332. Enable bool
  333. AccessTokenExpirationTime int64
  334. RefreshTokenExpirationTime int64
  335. InvalidateRefreshTokens bool
  336. JWTSecretBytes []byte `ini:"-"`
  337. JWTSecretBase64 string `ini:"JWT_SECRET"`
  338. MaxTokenLength int
  339. }{
  340. Enable: true,
  341. AccessTokenExpirationTime: 3600,
  342. RefreshTokenExpirationTime: 730,
  343. InvalidateRefreshTokens: false,
  344. MaxTokenLength: math.MaxInt16,
  345. }
  346. U2F = struct {
  347. AppID string
  348. TrustedFacets []string
  349. }{}
  350. // Metrics settings
  351. Metrics = struct {
  352. Enabled bool
  353. Token string
  354. }{
  355. Enabled: false,
  356. Token: "",
  357. }
  358. // I18n settings
  359. Langs []string
  360. Names []string
  361. // Highlight settings are loaded in modules/template/highlight.go
  362. // Other settings
  363. ShowFooterBranding bool
  364. ShowFooterVersion bool
  365. ShowFooterTemplateLoadTime bool
  366. // Global setting objects
  367. Cfg *ini.File
  368. CustomPath string // Custom directory path
  369. CustomConf string
  370. PIDFile = "/run/gitea.pid"
  371. WritePIDFile bool
  372. RunMode string
  373. RunUser string
  374. IsWindows bool
  375. HasRobotsTxt bool
  376. InternalToken string // internal access token
  377. )
  378. // IsProd if it's a production mode
  379. func IsProd() bool {
  380. return strings.EqualFold(RunMode, "prod")
  381. }
  382. func getAppPath() (string, error) {
  383. var appPath string
  384. var err error
  385. if IsWindows && filepath.IsAbs(os.Args[0]) {
  386. appPath = filepath.Clean(os.Args[0])
  387. } else {
  388. appPath, err = exec.LookPath(os.Args[0])
  389. }
  390. if err != nil {
  391. return "", err
  392. }
  393. appPath, err = filepath.Abs(appPath)
  394. if err != nil {
  395. return "", err
  396. }
  397. // Note: we don't use path.Dir here because it does not handle case
  398. // which path starts with two "/" in Windows: "//psf/Home/..."
  399. return strings.ReplaceAll(appPath, "\\", "/"), err
  400. }
  401. func getWorkPath(appPath string) string {
  402. workPath := AppWorkPath
  403. if giteaWorkPath, ok := os.LookupEnv("GITEA_WORK_DIR"); ok {
  404. workPath = giteaWorkPath
  405. }
  406. if len(workPath) == 0 {
  407. i := strings.LastIndex(appPath, "/")
  408. if i == -1 {
  409. workPath = appPath
  410. } else {
  411. workPath = appPath[:i]
  412. }
  413. }
  414. return strings.ReplaceAll(workPath, "\\", "/")
  415. }
  416. func init() {
  417. IsWindows = runtime.GOOS == "windows"
  418. // We can rely on log.CanColorStdout being set properly because modules/log/console_windows.go comes before modules/setting/setting.go lexicographically
  419. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "trace", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  420. var err error
  421. if AppPath, err = getAppPath(); err != nil {
  422. log.Fatal("Failed to get app path: %v", err)
  423. }
  424. AppWorkPath = getWorkPath(AppPath)
  425. }
  426. func forcePathSeparator(path string) {
  427. if strings.Contains(path, "\\") {
  428. log.Fatal("Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  429. }
  430. }
  431. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  432. // actual user that runs the app. The first return value is the actual user name.
  433. // This check is ignored under Windows since SSH remote login is not the main
  434. // method to login on Windows.
  435. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  436. if IsWindows || SSH.StartBuiltinServer {
  437. return "", true
  438. }
  439. currentUser := user.CurrentUsername()
  440. return currentUser, runUser == currentUser
  441. }
  442. func createPIDFile(pidPath string) {
  443. currentPid := os.Getpid()
  444. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  445. log.Fatal("Failed to create PID folder: %v", err)
  446. }
  447. file, err := os.Create(pidPath)
  448. if err != nil {
  449. log.Fatal("Failed to create PID file: %v", err)
  450. }
  451. defer file.Close()
  452. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  453. log.Fatal("Failed to write PID information: %v", err)
  454. }
  455. }
  456. // SetCustomPathAndConf will set CustomPath and CustomConf with reference to the
  457. // GITEA_CUSTOM environment variable and with provided overrides before stepping
  458. // back to the default
  459. func SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath string) {
  460. if len(providedWorkPath) != 0 {
  461. AppWorkPath = filepath.ToSlash(providedWorkPath)
  462. }
  463. if giteaCustom, ok := os.LookupEnv("GITEA_CUSTOM"); ok {
  464. CustomPath = giteaCustom
  465. }
  466. if len(providedCustom) != 0 {
  467. CustomPath = providedCustom
  468. }
  469. if len(CustomPath) == 0 {
  470. CustomPath = path.Join(AppWorkPath, "custom")
  471. } else if !filepath.IsAbs(CustomPath) {
  472. CustomPath = path.Join(AppWorkPath, CustomPath)
  473. }
  474. if len(providedConf) != 0 {
  475. CustomConf = providedConf
  476. }
  477. if len(CustomConf) == 0 {
  478. CustomConf = path.Join(CustomPath, "conf/app.ini")
  479. } else if !filepath.IsAbs(CustomConf) {
  480. CustomConf = path.Join(CustomPath, CustomConf)
  481. log.Warn("Using 'custom' directory as relative origin for configuration file: '%s'", CustomConf)
  482. }
  483. }
  484. // NewContext initializes configuration context.
  485. // NOTE: do not print any log except error.
  486. func NewContext() {
  487. Cfg = ini.Empty()
  488. if WritePIDFile && len(PIDFile) > 0 {
  489. createPIDFile(PIDFile)
  490. }
  491. isFile, err := util.IsFile(CustomConf)
  492. if err != nil {
  493. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  494. }
  495. if isFile {
  496. if err := Cfg.Append(CustomConf); err != nil {
  497. log.Fatal("Failed to load custom conf '%s': %v", CustomConf, err)
  498. }
  499. } else {
  500. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  501. }
  502. Cfg.NameMapper = ini.SnackCase
  503. homeDir, err := com.HomeDir()
  504. if err != nil {
  505. log.Fatal("Failed to get home directory: %v", err)
  506. }
  507. homeDir = strings.ReplaceAll(homeDir, "\\", "/")
  508. LogLevel = getLogLevel(Cfg.Section("log"), "LEVEL", log.INFO)
  509. StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None")
  510. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  511. forcePathSeparator(LogRootPath)
  512. RouterLogLevel = log.FromString(Cfg.Section("log").Key("ROUTER_LOG_LEVEL").MustString("Info"))
  513. sec := Cfg.Section("server")
  514. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  515. Protocol = HTTP
  516. switch sec.Key("PROTOCOL").String() {
  517. case "https":
  518. Protocol = HTTPS
  519. CertFile = sec.Key("CERT_FILE").String()
  520. KeyFile = sec.Key("KEY_FILE").String()
  521. if !filepath.IsAbs(CertFile) && len(CertFile) > 0 {
  522. CertFile = filepath.Join(CustomPath, CertFile)
  523. }
  524. if !filepath.IsAbs(KeyFile) && len(KeyFile) > 0 {
  525. KeyFile = filepath.Join(CustomPath, KeyFile)
  526. }
  527. case "fcgi":
  528. Protocol = FCGI
  529. case "fcgi+unix":
  530. Protocol = FCGIUnix
  531. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  532. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  533. if err != nil || UnixSocketPermissionParsed > 0777 {
  534. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  535. }
  536. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  537. case "unix":
  538. Protocol = UnixSocket
  539. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  540. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  541. if err != nil || UnixSocketPermissionParsed > 0777 {
  542. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  543. }
  544. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  545. }
  546. EnableLetsEncrypt = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  547. LetsEncryptTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  548. if !LetsEncryptTOS && EnableLetsEncrypt {
  549. log.Warn("Failed to enable Let's Encrypt due to Let's Encrypt TOS not being accepted")
  550. EnableLetsEncrypt = false
  551. }
  552. LetsEncryptDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  553. LetsEncryptEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  554. Domain = sec.Key("DOMAIN").MustString("localhost")
  555. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  556. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  557. GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
  558. GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
  559. StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)
  560. defaultAppURL := string(Protocol) + "://" + Domain
  561. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  562. defaultAppURL += ":" + HTTPPort
  563. }
  564. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL + "/")
  565. // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL.
  566. AppURL = strings.TrimRight(AppURL, "/") + "/"
  567. // Check if has app suburl.
  568. appURL, err := url.Parse(AppURL)
  569. if err != nil {
  570. log.Fatal("Invalid ROOT_URL '%s': %s", AppURL, err)
  571. }
  572. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  573. // This value is empty if site does not have sub-url.
  574. AppSubURL = strings.TrimSuffix(appURL.Path, "/")
  575. StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/")
  576. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  577. urlHostname := appURL.Hostname()
  578. if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" {
  579. Domain = urlHostname
  580. }
  581. AbsoluteAssetURL = MakeAbsoluteAssetURL(AppURL, StaticURLPrefix)
  582. manifestBytes := MakeManifestData(AppName, AppURL, AbsoluteAssetURL)
  583. ManifestData = `application/json;base64,` + base64.StdEncoding.EncodeToString(manifestBytes)
  584. var defaultLocalURL string
  585. switch Protocol {
  586. case UnixSocket:
  587. defaultLocalURL = "http://unix/"
  588. case FCGI:
  589. defaultLocalURL = AppURL
  590. case FCGIUnix:
  591. defaultLocalURL = AppURL
  592. default:
  593. defaultLocalURL = string(Protocol) + "://"
  594. if HTTPAddr == "0.0.0.0" {
  595. defaultLocalURL += net.JoinHostPort("localhost", HTTPPort) + "/"
  596. } else {
  597. defaultLocalURL += net.JoinHostPort(HTTPAddr, HTTPPort) + "/"
  598. }
  599. }
  600. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  601. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  602. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  603. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  604. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  605. if len(StaticRootPath) == 0 {
  606. StaticRootPath = AppWorkPath
  607. }
  608. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(StaticRootPath)
  609. StaticCacheTime = sec.Key("STATIC_CACHE_TIME").MustDuration(6 * time.Hour)
  610. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  611. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  612. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  613. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  614. if !filepath.IsAbs(PprofDataPath) {
  615. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  616. }
  617. switch sec.Key("LANDING_PAGE").MustString("home") {
  618. case "explore":
  619. LandingPageURL = LandingPageExplore
  620. case "organizations":
  621. LandingPageURL = LandingPageOrganizations
  622. case "login":
  623. LandingPageURL = LandingPageLogin
  624. default:
  625. LandingPageURL = LandingPageHome
  626. }
  627. if len(SSH.Domain) == 0 {
  628. SSH.Domain = Domain
  629. }
  630. SSH.RootPath = path.Join(homeDir, ".ssh")
  631. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  632. if len(serverCiphers) > 0 {
  633. SSH.ServerCiphers = serverCiphers
  634. }
  635. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  636. if len(serverKeyExchanges) > 0 {
  637. SSH.ServerKeyExchanges = serverKeyExchanges
  638. }
  639. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  640. if len(serverMACs) > 0 {
  641. SSH.ServerMACs = serverMACs
  642. }
  643. SSH.KeyTestPath = os.TempDir()
  644. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  645. log.Fatal("Failed to map SSH settings: %v", err)
  646. }
  647. for i, key := range SSH.ServerHostKeys {
  648. if !filepath.IsAbs(key) {
  649. SSH.ServerHostKeys[i] = filepath.Join(AppDataPath, key)
  650. }
  651. }
  652. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  653. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  654. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  655. // When disable SSH, start builtin server value is ignored.
  656. if SSH.Disabled {
  657. SSH.StartBuiltinServer = false
  658. }
  659. trustedUserCaKeys := sec.Key("SSH_TRUSTED_USER_CA_KEYS").Strings(",")
  660. for _, caKey := range trustedUserCaKeys {
  661. pubKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(caKey))
  662. if err != nil {
  663. log.Fatal("Failed to parse TrustedUserCaKeys: %s %v", caKey, err)
  664. }
  665. SSH.TrustedUserCAKeysParsed = append(SSH.TrustedUserCAKeysParsed, pubKey)
  666. }
  667. if len(trustedUserCaKeys) > 0 {
  668. // Set the default as email,username otherwise we can leave it empty
  669. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("username,email")
  670. } else {
  671. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("off")
  672. }
  673. SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(","))
  674. if !SSH.Disabled && !SSH.StartBuiltinServer {
  675. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  676. log.Fatal("Failed to create '%s': %v", SSH.RootPath, err)
  677. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  678. log.Fatal("Failed to create '%s': %v", SSH.KeyTestPath, err)
  679. }
  680. if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled {
  681. fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem"))
  682. if err := ioutil.WriteFile(fname,
  683. []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil {
  684. log.Fatal("Failed to create '%s': %v", fname, err)
  685. }
  686. }
  687. }
  688. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool(SSH.MinimumKeySizeCheck)
  689. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  690. for _, key := range minimumKeySizes {
  691. if key.MustInt() != -1 {
  692. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  693. } else {
  694. delete(SSH.MinimumKeySizes, strings.ToLower(key.Name()))
  695. }
  696. }
  697. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  698. SSH.CreateAuthorizedKeysFile = sec.Key("SSH_CREATE_AUTHORIZED_KEYS_FILE").MustBool(true)
  699. SSH.AuthorizedPrincipalsBackup = false
  700. SSH.CreateAuthorizedPrincipalsFile = false
  701. if SSH.AuthorizedPrincipalsEnabled {
  702. SSH.AuthorizedPrincipalsBackup = sec.Key("SSH_AUTHORIZED_PRINCIPALS_BACKUP").MustBool(true)
  703. SSH.CreateAuthorizedPrincipalsFile = sec.Key("SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE").MustBool(true)
  704. }
  705. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  706. if err = Cfg.Section("oauth2").MapTo(&OAuth2); err != nil {
  707. log.Fatal("Failed to OAuth2 settings: %v", err)
  708. return
  709. }
  710. if OAuth2.Enable {
  711. OAuth2.JWTSecretBytes = make([]byte, 32)
  712. n, err := base64.RawURLEncoding.Decode(OAuth2.JWTSecretBytes, []byte(OAuth2.JWTSecretBase64))
  713. if err != nil || n != 32 {
  714. OAuth2.JWTSecretBase64, err = generate.NewJwtSecret()
  715. if err != nil {
  716. log.Fatal("error generating JWT secret: %v", err)
  717. return
  718. }
  719. cfg := ini.Empty()
  720. isFile, err := util.IsFile(CustomConf)
  721. if err != nil {
  722. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  723. }
  724. if isFile {
  725. if err := cfg.Append(CustomConf); err != nil {
  726. log.Error("failed to load custom conf %s: %v", CustomConf, err)
  727. return
  728. }
  729. }
  730. cfg.Section("oauth2").Key("JWT_SECRET").SetValue(OAuth2.JWTSecretBase64)
  731. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  732. log.Fatal("failed to create '%s': %v", CustomConf, err)
  733. return
  734. }
  735. if err := cfg.SaveTo(CustomConf); err != nil {
  736. log.Fatal("error saving generating JWT secret to custom config: %v", err)
  737. return
  738. }
  739. }
  740. }
  741. sec = Cfg.Section("admin")
  742. Admin.DefaultEmailNotification = sec.Key("DEFAULT_EMAIL_NOTIFICATIONS").MustString("enabled")
  743. sec = Cfg.Section("security")
  744. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  745. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  746. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  747. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  748. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  749. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  750. ReverseProxyAuthEmail = sec.Key("REVERSE_PROXY_AUTHENTICATION_EMAIL").MustString("X-WEBAUTH-EMAIL")
  751. ReverseProxyLimit = sec.Key("REVERSE_PROXY_LIMIT").MustInt(1)
  752. ReverseProxyTrustedProxies = sec.Key("REVERSE_PROXY_TRUSTED_PROXIES").Strings(",")
  753. if len(ReverseProxyTrustedProxies) == 0 {
  754. ReverseProxyTrustedProxies = []string{"127.0.0.0/8", "::1/128"}
  755. }
  756. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  757. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  758. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(true)
  759. DisableWebhooks = sec.Key("DISABLE_WEBHOOKS").MustBool(false)
  760. OnlyAllowPushIfGiteaEnvironmentSet = sec.Key("ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET").MustBool(true)
  761. PasswordHashAlgo = sec.Key("PASSWORD_HASH_ALGO").MustString("pbkdf2")
  762. CSRFCookieHTTPOnly = sec.Key("CSRF_COOKIE_HTTP_ONLY").MustBool(true)
  763. PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
  764. InternalToken = loadInternalToken(sec)
  765. cfgdata := sec.Key("PASSWORD_COMPLEXITY").Strings(",")
  766. if len(cfgdata) == 0 {
  767. cfgdata = []string{"off"}
  768. }
  769. PasswordComplexity = make([]string, 0, len(cfgdata))
  770. for _, name := range cfgdata {
  771. name := strings.ToLower(strings.Trim(name, `"`))
  772. if name != "" {
  773. PasswordComplexity = append(PasswordComplexity, name)
  774. }
  775. }
  776. newAttachmentService()
  777. newLFSService()
  778. timeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("")
  779. if timeFormatKey != "" {
  780. TimeFormat = map[string]string{
  781. "ANSIC": time.ANSIC,
  782. "UnixDate": time.UnixDate,
  783. "RubyDate": time.RubyDate,
  784. "RFC822": time.RFC822,
  785. "RFC822Z": time.RFC822Z,
  786. "RFC850": time.RFC850,
  787. "RFC1123": time.RFC1123,
  788. "RFC1123Z": time.RFC1123Z,
  789. "RFC3339": time.RFC3339,
  790. "RFC3339Nano": time.RFC3339Nano,
  791. "Kitchen": time.Kitchen,
  792. "Stamp": time.Stamp,
  793. "StampMilli": time.StampMilli,
  794. "StampMicro": time.StampMicro,
  795. "StampNano": time.StampNano,
  796. }[timeFormatKey]
  797. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  798. if len(TimeFormat) == 0 {
  799. TimeFormat = timeFormatKey
  800. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  801. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  802. log.Warn("Provided TimeFormat: %s does not create a fully specified date and time.", TimeFormat)
  803. log.Warn("In order to display dates and times correctly please check your time format has 2006, 01, 02, 15, 04 and 05")
  804. }
  805. log.Trace("Custom TimeFormat: %s", TimeFormat)
  806. }
  807. }
  808. zone := Cfg.Section("time").Key("DEFAULT_UI_LOCATION").String()
  809. if zone != "" {
  810. DefaultUILocation, err = time.LoadLocation(zone)
  811. if err != nil {
  812. log.Fatal("Load time zone failed: %v", err)
  813. } else {
  814. log.Info("Default UI Location is %v", zone)
  815. }
  816. }
  817. if DefaultUILocation == nil {
  818. DefaultUILocation = time.Local
  819. }
  820. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  821. RunMode = Cfg.Section("").Key("RUN_MODE").MustString("prod")
  822. // Does not check run user when the install lock is off.
  823. if InstallLock {
  824. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  825. if !match {
  826. log.Fatal("Expect user '%s' but current user is: %s", RunUser, currentUser)
  827. }
  828. }
  829. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  830. newRepository()
  831. newPictureService()
  832. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  833. log.Fatal("Failed to map UI settings: %v", err)
  834. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  835. log.Fatal("Failed to map Markdown settings: %v", err)
  836. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  837. log.Fatal("Fail to map Admin settings: %v", err)
  838. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  839. log.Fatal("Failed to map API settings: %v", err)
  840. } else if err = Cfg.Section("metrics").MapTo(&Metrics); err != nil {
  841. log.Fatal("Failed to map Metrics settings: %v", err)
  842. }
  843. u := *appURL
  844. u.Path = path.Join(u.Path, "api", "swagger")
  845. API.SwaggerURL = u.String()
  846. newGit()
  847. sec = Cfg.Section("mirror")
  848. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  849. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  850. if Mirror.MinInterval.Minutes() < 1 {
  851. log.Warn("Mirror.MinInterval is too low")
  852. Mirror.MinInterval = 1 * time.Minute
  853. }
  854. if Mirror.DefaultInterval < Mirror.MinInterval {
  855. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  856. Mirror.DefaultInterval = time.Hour * 8
  857. }
  858. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  859. if len(Langs) == 0 {
  860. Langs = []string{
  861. "en-US", "zh-CN", "zh-HK", "zh-TW", "de-DE", "fr-FR", "nl-NL", "lv-LV",
  862. "ru-RU", "uk-UA", "ja-JP", "es-ES", "pt-BR", "pt-PT", "pl-PL", "bg-BG",
  863. "it-IT", "fi-FI", "tr-TR", "cs-CZ", "sr-SP", "sv-SE", "ko-KR"}
  864. }
  865. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  866. if len(Names) == 0 {
  867. Names = []string{"English", "简体中文", "繁體中文(香港)", "繁體中文(台灣)", "Deutsch",
  868. "français", "Nederlands", "latviešu", "русский", "Українська", "日本語",
  869. "español", "português do Brasil", "Português de Portugal", "polski", "български",
  870. "italiano", "suomi", "Türkçe", "čeština", "српски", "svenska", "한국어"}
  871. }
  872. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  873. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  874. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  875. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  876. UI.DefaultShowFullName = Cfg.Section("ui").Key("DEFAULT_SHOW_FULL_NAME").MustBool(false)
  877. UI.SearchRepoDescription = Cfg.Section("ui").Key("SEARCH_REPO_DESCRIPTION").MustBool(true)
  878. UI.UseServiceWorker = Cfg.Section("ui").Key("USE_SERVICE_WORKER").MustBool(true)
  879. HasRobotsTxt, err = util.IsFile(path.Join(CustomPath, "robots.txt"))
  880. if err != nil {
  881. log.Error("Unable to check if %s is a file. Error: %v", path.Join(CustomPath, "robots.txt"), err)
  882. }
  883. newMarkup()
  884. sec = Cfg.Section("U2F")
  885. U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimSuffix(AppURL, AppSubURL+"/")))
  886. U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimSuffix(AppURL, "/"))
  887. UI.ReactionsMap = make(map[string]bool)
  888. for _, reaction := range UI.Reactions {
  889. UI.ReactionsMap[reaction] = true
  890. }
  891. }
  892. func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) {
  893. anything := false
  894. email := false
  895. username := false
  896. for _, value := range values {
  897. v := strings.ToLower(strings.TrimSpace(value))
  898. switch v {
  899. case "off":
  900. return []string{"off"}, false
  901. case "email":
  902. email = true
  903. case "username":
  904. username = true
  905. case "anything":
  906. anything = true
  907. }
  908. }
  909. if anything {
  910. return []string{"anything"}, true
  911. }
  912. authorizedPrincipalsAllow := []string{}
  913. if username {
  914. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "username")
  915. }
  916. if email {
  917. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "email")
  918. }
  919. return authorizedPrincipalsAllow, true
  920. }
  921. func loadInternalToken(sec *ini.Section) string {
  922. uri := sec.Key("INTERNAL_TOKEN_URI").String()
  923. if len(uri) == 0 {
  924. return loadOrGenerateInternalToken(sec)
  925. }
  926. tempURI, err := url.Parse(uri)
  927. if err != nil {
  928. log.Fatal("Failed to parse INTERNAL_TOKEN_URI (%s): %v", uri, err)
  929. }
  930. switch tempURI.Scheme {
  931. case "file":
  932. fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0600)
  933. if err != nil {
  934. log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err)
  935. }
  936. defer fp.Close()
  937. buf, err := ioutil.ReadAll(fp)
  938. if err != nil {
  939. log.Fatal("Failed to read InternalTokenURI (%s): %v", uri, err)
  940. }
  941. // No token in the file, generate one and store it.
  942. if len(buf) == 0 {
  943. token, err := generate.NewInternalToken()
  944. if err != nil {
  945. log.Fatal("Error generate internal token: %v", err)
  946. }
  947. if _, err := io.WriteString(fp, token); err != nil {
  948. log.Fatal("Error writing to InternalTokenURI (%s): %v", uri, err)
  949. }
  950. return token
  951. }
  952. return strings.TrimSpace(string(buf))
  953. default:
  954. log.Fatal("Unsupported URI-Scheme %q (INTERNAL_TOKEN_URI = %q)", tempURI.Scheme, uri)
  955. }
  956. return ""
  957. }
  958. func loadOrGenerateInternalToken(sec *ini.Section) string {
  959. var err error
  960. token := sec.Key("INTERNAL_TOKEN").String()
  961. if len(token) == 0 {
  962. token, err = generate.NewInternalToken()
  963. if err != nil {
  964. log.Fatal("Error generate internal token: %v", err)
  965. }
  966. // Save secret
  967. cfgSave := ini.Empty()
  968. isFile, err := util.IsFile(CustomConf)
  969. if err != nil {
  970. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  971. }
  972. if isFile {
  973. // Keeps custom settings if there is already something.
  974. if err := cfgSave.Append(CustomConf); err != nil {
  975. log.Error("Failed to load custom conf '%s': %v", CustomConf, err)
  976. }
  977. }
  978. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(token)
  979. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  980. log.Fatal("Failed to create '%s': %v", CustomConf, err)
  981. }
  982. if err := cfgSave.SaveTo(CustomConf); err != nil {
  983. log.Fatal("Error saving generated INTERNAL_TOKEN to custom config: %v", err)
  984. }
  985. }
  986. return token
  987. }
  988. // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
  989. func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string {
  990. parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/"))
  991. if err != nil {
  992. log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err)
  993. }
  994. if err == nil && parsedPrefix.Hostname() == "" {
  995. if staticURLPrefix == "" {
  996. return strings.TrimSuffix(appURL, "/")
  997. }
  998. // StaticURLPrefix is just a path
  999. return util.URLJoin(appURL, strings.TrimSuffix(staticURLPrefix, "/"))
  1000. }
  1001. return strings.TrimSuffix(staticURLPrefix, "/")
  1002. }
  1003. // MakeManifestData generates web app manifest JSON
  1004. func MakeManifestData(appName string, appURL string, absoluteAssetURL string) []byte {
  1005. type manifestIcon struct {
  1006. Src string `json:"src"`
  1007. Type string `json:"type"`
  1008. Sizes string `json:"sizes"`
  1009. }
  1010. type manifestJSON struct {
  1011. Name string `json:"name"`
  1012. ShortName string `json:"short_name"`
  1013. StartURL string `json:"start_url"`
  1014. Icons []manifestIcon `json:"icons"`
  1015. }
  1016. json := jsoniter.ConfigCompatibleWithStandardLibrary
  1017. bytes, err := json.Marshal(&manifestJSON{
  1018. Name: appName,
  1019. ShortName: appName,
  1020. StartURL: appURL,
  1021. Icons: []manifestIcon{
  1022. {
  1023. Src: absoluteAssetURL + "/img/logo.png",
  1024. Type: "image/png",
  1025. Sizes: "512x512",
  1026. },
  1027. {
  1028. Src: absoluteAssetURL + "/img/logo.svg",
  1029. Type: "image/svg+xml",
  1030. Sizes: "512x512",
  1031. },
  1032. },
  1033. })
  1034. if err != nil {
  1035. log.Error("unable to marshal manifest JSON. Error: %v", err)
  1036. return make([]byte, 0)
  1037. }
  1038. return bytes
  1039. }
  1040. // NewServices initializes the services
  1041. func NewServices() {
  1042. InitDBConfig()
  1043. newService()
  1044. NewLogServices(false)
  1045. newCacheService()
  1046. newSessionService()
  1047. newCORSService()
  1048. newMailService()
  1049. newRegisterMailService()
  1050. newNotifyMailService()
  1051. newWebhookService()
  1052. newMigrationsService()
  1053. newIndexerService()
  1054. newTaskService()
  1055. NewQueueService()
  1056. newProject()
  1057. }