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

setting.go 28 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
9 years ago
11 years ago
11 years ago
9 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
10 years ago
10 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package setting
  5. import (
  6. "fmt"
  7. "net/mail"
  8. "net/url"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/user"
  19. "github.com/Unknwon/com"
  20. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  21. _ "github.com/go-macaron/cache/redis"
  22. "github.com/go-macaron/session"
  23. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  24. _ "github.com/kardianos/minwinsvc" // import minwinsvc for windows services
  25. "gopkg.in/ini.v1"
  26. "strk.kbt.io/projects/go/libravatar"
  27. )
  28. // Scheme describes protocol types
  29. type Scheme string
  30. // enumerates all the scheme types
  31. const (
  32. HTTP Scheme = "http"
  33. HTTPS Scheme = "https"
  34. FCGI Scheme = "fcgi"
  35. UnixSocket Scheme = "unix"
  36. )
  37. // LandingPage describes the default page
  38. type LandingPage string
  39. // enumerates all the landing page types
  40. const (
  41. LandingPageHome LandingPage = "/"
  42. LandingPageExplore LandingPage = "/explore"
  43. )
  44. // settings
  45. var (
  46. // AppVer settings
  47. AppVer string
  48. AppName string
  49. AppURL string
  50. AppSubURL string
  51. AppSubURLDepth int // Number of slashes
  52. AppPath string
  53. AppDataPath string
  54. // Server settings
  55. Protocol Scheme
  56. Domain string
  57. HTTPAddr string
  58. HTTPPort string
  59. LocalURL string
  60. OfflineMode bool
  61. DisableRouterLog bool
  62. CertFile string
  63. KeyFile string
  64. StaticRootPath string
  65. EnableGzip bool
  66. LandingPageURL LandingPage
  67. UnixSocketPermission uint32
  68. SSH struct {
  69. Disabled bool `ini:"DISABLE_SSH"`
  70. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  71. Domain string `ini:"SSH_DOMAIN"`
  72. Port int `ini:"SSH_PORT"`
  73. ListenHost string `ini:"SSH_LISTEN_HOST"`
  74. ListenPort int `ini:"SSH_LISTEN_PORT"`
  75. RootPath string `ini:"SSH_ROOT_PATH"`
  76. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  77. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  78. MinimumKeySizeCheck bool `ini:"-"`
  79. MinimumKeySizes map[string]int `ini:"-"`
  80. }
  81. // Security settings
  82. InstallLock bool
  83. SecretKey string
  84. LogInRememberDays int
  85. CookieUserName string
  86. CookieRememberName string
  87. ReverseProxyAuthUser string
  88. // Database settings
  89. UseSQLite3 bool
  90. UseMySQL bool
  91. UsePostgreSQL bool
  92. UseTiDB bool
  93. // Webhook settings
  94. Webhook = struct {
  95. QueueLength int
  96. DeliverTimeout int
  97. SkipTLSVerify bool
  98. Types []string
  99. PagingNum int
  100. }{
  101. QueueLength: 1000,
  102. DeliverTimeout: 5,
  103. SkipTLSVerify: false,
  104. PagingNum: 10,
  105. }
  106. // Repository settings
  107. Repository = struct {
  108. AnsiCharset string
  109. ForcePrivate bool
  110. MaxCreationLimit int
  111. MirrorQueueLength int
  112. PullRequestQueueLength int
  113. PreferredLicenses []string
  114. DisableHTTPGit bool
  115. // Repository editor settings
  116. Editor struct {
  117. LineWrapExtensions []string
  118. PreviewableFileModes []string
  119. } `ini:"-"`
  120. // Repository upload settings
  121. Upload struct {
  122. Enabled bool
  123. TempPath string
  124. AllowedTypes []string `delim:"|"`
  125. FileMaxSize int64
  126. MaxFiles int
  127. } `ini:"-"`
  128. }{
  129. AnsiCharset: "",
  130. ForcePrivate: false,
  131. MaxCreationLimit: -1,
  132. MirrorQueueLength: 1000,
  133. PullRequestQueueLength: 1000,
  134. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  135. DisableHTTPGit: false,
  136. // Repository editor settings
  137. Editor: struct {
  138. LineWrapExtensions []string
  139. PreviewableFileModes []string
  140. }{
  141. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  142. PreviewableFileModes: []string{"markdown"},
  143. },
  144. // Repository upload settings
  145. Upload: struct {
  146. Enabled bool
  147. TempPath string
  148. AllowedTypes []string `delim:"|"`
  149. FileMaxSize int64
  150. MaxFiles int
  151. }{
  152. Enabled: true,
  153. TempPath: "data/tmp/uploads",
  154. AllowedTypes: []string{},
  155. FileMaxSize: 3,
  156. MaxFiles: 5,
  157. },
  158. }
  159. RepoRootPath string
  160. ScriptType = "bash"
  161. // UI settings
  162. UI = struct {
  163. ExplorePagingNum int
  164. IssuePagingNum int
  165. FeedMaxCommitNum int
  166. ThemeColorMetaTag string
  167. MaxDisplayFileSize int64
  168. Admin struct {
  169. UserPagingNum int
  170. RepoPagingNum int
  171. NoticePagingNum int
  172. OrgPagingNum int
  173. } `ini:"ui.admin"`
  174. User struct {
  175. RepoPagingNum int
  176. } `ini:"ui.user"`
  177. }{
  178. ExplorePagingNum: 20,
  179. IssuePagingNum: 10,
  180. FeedMaxCommitNum: 5,
  181. ThemeColorMetaTag: `#6cc644`,
  182. MaxDisplayFileSize: 8388608,
  183. Admin: struct {
  184. UserPagingNum int
  185. RepoPagingNum int
  186. NoticePagingNum int
  187. OrgPagingNum int
  188. }{
  189. UserPagingNum: 50,
  190. RepoPagingNum: 50,
  191. NoticePagingNum: 25,
  192. OrgPagingNum: 50,
  193. },
  194. User: struct {
  195. RepoPagingNum int
  196. }{
  197. RepoPagingNum: 15,
  198. },
  199. }
  200. // Markdown sttings
  201. Markdown = struct {
  202. EnableHardLineBreak bool
  203. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  204. FileExtensions []string
  205. }{
  206. EnableHardLineBreak: false,
  207. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  208. }
  209. // Picture settings
  210. AvatarUploadPath string
  211. GravatarSource string
  212. DisableGravatar bool
  213. EnableFederatedAvatar bool
  214. LibravatarService *libravatar.Libravatar
  215. // Log settings
  216. LogRootPath string
  217. LogModes []string
  218. LogConfigs []string
  219. // Attachment settings
  220. AttachmentPath string
  221. AttachmentAllowedTypes string
  222. AttachmentMaxSize int64
  223. AttachmentMaxFiles int
  224. AttachmentEnabled bool
  225. // Time settings
  226. TimeFormat string
  227. // Cache settings
  228. CacheAdapter string
  229. CacheInterval int
  230. CacheConn string
  231. // Session settings
  232. SessionConfig session.Options
  233. CSRFCookieName = "_csrf"
  234. // Cron tasks
  235. Cron = struct {
  236. UpdateMirror struct {
  237. Enabled bool
  238. RunAtStart bool
  239. Schedule string
  240. } `ini:"cron.update_mirrors"`
  241. RepoHealthCheck struct {
  242. Enabled bool
  243. RunAtStart bool
  244. Schedule string
  245. Timeout time.Duration
  246. Args []string `delim:" "`
  247. } `ini:"cron.repo_health_check"`
  248. CheckRepoStats struct {
  249. Enabled bool
  250. RunAtStart bool
  251. Schedule string
  252. } `ini:"cron.check_repo_stats"`
  253. }{
  254. UpdateMirror: struct {
  255. Enabled bool
  256. RunAtStart bool
  257. Schedule string
  258. }{
  259. Schedule: "@every 10m",
  260. },
  261. RepoHealthCheck: struct {
  262. Enabled bool
  263. RunAtStart bool
  264. Schedule string
  265. Timeout time.Duration
  266. Args []string `delim:" "`
  267. }{
  268. Schedule: "@every 24h",
  269. Timeout: 60 * time.Second,
  270. Args: []string{},
  271. },
  272. CheckRepoStats: struct {
  273. Enabled bool
  274. RunAtStart bool
  275. Schedule string
  276. }{
  277. RunAtStart: true,
  278. Schedule: "@every 24h",
  279. },
  280. }
  281. // Git settings
  282. Git = struct {
  283. DisableDiffHighlight bool
  284. MaxGitDiffLines int
  285. MaxGitDiffLineCharacters int
  286. MaxGitDiffFiles int
  287. GCArgs []string `delim:" "`
  288. Timeout struct {
  289. Migrate int
  290. Mirror int
  291. Clone int
  292. Pull int
  293. GC int `ini:"GC"`
  294. } `ini:"git.timeout"`
  295. }{
  296. DisableDiffHighlight: false,
  297. MaxGitDiffLines: 1000,
  298. MaxGitDiffLineCharacters: 500,
  299. MaxGitDiffFiles: 100,
  300. GCArgs: []string{},
  301. Timeout: struct {
  302. Migrate int
  303. Mirror int
  304. Clone int
  305. Pull int
  306. GC int `ini:"GC"`
  307. }{
  308. Migrate: 600,
  309. Mirror: 300,
  310. Clone: 300,
  311. Pull: 300,
  312. GC: 60,
  313. },
  314. }
  315. // Mirror settings
  316. Mirror = struct {
  317. DefaultInterval int
  318. }{
  319. DefaultInterval: 8,
  320. }
  321. // API settings
  322. API = struct {
  323. MaxResponseItems int
  324. }{
  325. MaxResponseItems: 50,
  326. }
  327. // I18n settings
  328. Langs []string
  329. Names []string
  330. dateLangs map[string]string
  331. // Highlight settings are loaded in modules/template/hightlight.go
  332. // Other settings
  333. ShowFooterBranding bool
  334. ShowFooterVersion bool
  335. ShowFooterTemplateLoadTime bool
  336. // Global setting objects
  337. Cfg *ini.File
  338. CustomPath string // Custom directory path
  339. CustomConf string
  340. ProdMode bool
  341. RunUser string
  342. IsWindows bool
  343. HasRobotsTxt bool
  344. )
  345. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  346. func DateLang(lang string) string {
  347. name, ok := dateLangs[lang]
  348. if ok {
  349. return name
  350. }
  351. return "en"
  352. }
  353. // execPath returns the executable path.
  354. func execPath() (string, error) {
  355. file, err := exec.LookPath(os.Args[0])
  356. if err != nil {
  357. return "", err
  358. }
  359. return filepath.Abs(file)
  360. }
  361. func init() {
  362. IsWindows = runtime.GOOS == "windows"
  363. log.NewLogger(0, "console", `{"level": 0}`)
  364. var err error
  365. if AppPath, err = execPath(); err != nil {
  366. log.Fatal(4, "fail to get app path: %v\n", err)
  367. }
  368. // Note: we don't use path.Dir here because it does not handle case
  369. // which path starts with two "/" in Windows: "//psf/Home/..."
  370. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  371. }
  372. // WorkDir returns absolute path of work directory.
  373. func WorkDir() (string, error) {
  374. wd := os.Getenv("GITEA_WORK_DIR")
  375. if len(wd) > 0 {
  376. return wd, nil
  377. }
  378. // Use GOGS_WORK_DIR if available, for backward compatibility
  379. // TODO: drop in 1.1.0 ?
  380. wd = os.Getenv("GOGS_WORK_DIR")
  381. if len(wd) > 0 {
  382. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  383. please consider changing to GITEA_WORK_DIR`)
  384. return wd, nil
  385. }
  386. i := strings.LastIndex(AppPath, "/")
  387. if i == -1 {
  388. return AppPath, nil
  389. }
  390. return AppPath[:i], nil
  391. }
  392. func forcePathSeparator(path string) {
  393. if strings.Contains(path, "\\") {
  394. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  395. }
  396. }
  397. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  398. // actual user that runs the app. The first return value is the actual user name.
  399. // This check is ignored under Windows since SSH remote login is not the main
  400. // method to login on Windows.
  401. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  402. if IsWindows {
  403. return "", true
  404. }
  405. currentUser := user.CurrentUsername()
  406. return currentUser, runUser == currentUser
  407. }
  408. // NewContext initializes configuration context.
  409. // NOTE: do not print any log except error.
  410. func NewContext() {
  411. workDir, err := WorkDir()
  412. if err != nil {
  413. log.Fatal(4, "Fail to get work directory: %v", err)
  414. }
  415. Cfg = ini.Empty()
  416. if err != nil {
  417. log.Fatal(4, "Fail to parse 'app.ini': %v", err)
  418. }
  419. CustomPath = os.Getenv("GITEA_CUSTOM")
  420. if len(CustomPath) == 0 {
  421. // For backward compatibility
  422. // TODO: drop in 1.1.0 ?
  423. CustomPath = os.Getenv("GOGS_CUSTOM")
  424. if len(CustomPath) == 0 {
  425. CustomPath = workDir + "/custom"
  426. } else {
  427. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  428. please consider changing to GITEA_CUSTOM`)
  429. }
  430. }
  431. if len(CustomConf) == 0 {
  432. CustomConf = CustomPath + "/conf/app.ini"
  433. }
  434. if com.IsFile(CustomConf) {
  435. if err = Cfg.Append(CustomConf); err != nil {
  436. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  437. }
  438. } else {
  439. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  440. }
  441. Cfg.NameMapper = ini.AllCapsUnderscore
  442. homeDir, err := com.HomeDir()
  443. if err != nil {
  444. log.Fatal(4, "Fail to get home directory: %v", err)
  445. }
  446. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  447. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  448. forcePathSeparator(LogRootPath)
  449. sec := Cfg.Section("server")
  450. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  451. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  452. if AppURL[len(AppURL)-1] != '/' {
  453. AppURL += "/"
  454. }
  455. // Check if has app suburl.
  456. url, err := url.Parse(AppURL)
  457. if err != nil {
  458. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  459. }
  460. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  461. // This value is empty if site does not have sub-url.
  462. AppSubURL = strings.TrimSuffix(url.Path, "/")
  463. AppSubURLDepth = strings.Count(AppSubURL, "/")
  464. Protocol = HTTP
  465. if sec.Key("PROTOCOL").String() == "https" {
  466. Protocol = HTTPS
  467. CertFile = sec.Key("CERT_FILE").String()
  468. KeyFile = sec.Key("KEY_FILE").String()
  469. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  470. Protocol = FCGI
  471. } else if sec.Key("PROTOCOL").String() == "unix" {
  472. Protocol = UnixSocket
  473. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  474. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  475. if err != nil || UnixSocketPermissionParsed > 0777 {
  476. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  477. }
  478. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  479. }
  480. Domain = sec.Key("DOMAIN").MustString("localhost")
  481. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  482. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  483. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  484. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  485. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  486. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  487. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  488. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  489. switch sec.Key("LANDING_PAGE").MustString("home") {
  490. case "explore":
  491. LandingPageURL = LandingPageExplore
  492. default:
  493. LandingPageURL = LandingPageHome
  494. }
  495. SSH.RootPath = path.Join(homeDir, ".ssh")
  496. SSH.KeyTestPath = os.TempDir()
  497. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  498. log.Fatal(4, "Fail to map SSH settings: %v", err)
  499. }
  500. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  501. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  502. // When disable SSH, start builtin server value is ignored.
  503. if SSH.Disabled {
  504. SSH.StartBuiltinServer = false
  505. }
  506. if !SSH.Disabled && !SSH.StartBuiltinServer {
  507. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  508. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  509. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  510. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  511. }
  512. }
  513. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  514. SSH.MinimumKeySizes = map[string]int{}
  515. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  516. for _, key := range minimumKeySizes {
  517. if key.MustInt() != -1 {
  518. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  519. }
  520. }
  521. sec = Cfg.Section("security")
  522. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  523. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  524. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  525. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  526. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  527. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  528. sec = Cfg.Section("attachment")
  529. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  530. if !filepath.IsAbs(AttachmentPath) {
  531. AttachmentPath = path.Join(workDir, AttachmentPath)
  532. }
  533. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  534. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  535. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  536. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  537. TimeFormat = map[string]string{
  538. "ANSIC": time.ANSIC,
  539. "UnixDate": time.UnixDate,
  540. "RubyDate": time.RubyDate,
  541. "RFC822": time.RFC822,
  542. "RFC822Z": time.RFC822Z,
  543. "RFC850": time.RFC850,
  544. "RFC1123": time.RFC1123,
  545. "RFC1123Z": time.RFC1123Z,
  546. "RFC3339": time.RFC3339,
  547. "RFC3339Nano": time.RFC3339Nano,
  548. "Kitchen": time.Kitchen,
  549. "Stamp": time.Stamp,
  550. "StampMilli": time.StampMilli,
  551. "StampMicro": time.StampMicro,
  552. "StampNano": time.StampNano,
  553. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  554. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  555. // Does not check run user when the install lock is off.
  556. if InstallLock {
  557. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  558. if !match {
  559. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  560. }
  561. }
  562. // Determine and create root git repository path.
  563. sec = Cfg.Section("repository")
  564. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  565. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  566. forcePathSeparator(RepoRootPath)
  567. if !filepath.IsAbs(RepoRootPath) {
  568. RepoRootPath = path.Join(workDir, RepoRootPath)
  569. } else {
  570. RepoRootPath = path.Clean(RepoRootPath)
  571. }
  572. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  573. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  574. log.Fatal(4, "Fail to map Repository settings: %v", err)
  575. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  576. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  577. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  578. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  579. }
  580. if !filepath.IsAbs(Repository.Upload.TempPath) {
  581. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  582. }
  583. sec = Cfg.Section("picture")
  584. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  585. forcePathSeparator(AvatarUploadPath)
  586. if !filepath.IsAbs(AvatarUploadPath) {
  587. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  588. }
  589. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  590. case "duoshuo":
  591. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  592. case "gravatar":
  593. GravatarSource = "https://secure.gravatar.com/avatar/"
  594. case "libravatar":
  595. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  596. default:
  597. GravatarSource = source
  598. }
  599. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  600. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  601. if OfflineMode {
  602. DisableGravatar = true
  603. EnableFederatedAvatar = false
  604. }
  605. if DisableGravatar {
  606. EnableFederatedAvatar = false
  607. }
  608. if EnableFederatedAvatar {
  609. LibravatarService = libravatar.New()
  610. parts := strings.Split(GravatarSource, "/")
  611. if len(parts) >= 3 {
  612. if parts[0] == "https:" {
  613. LibravatarService.SetUseHTTPS(true)
  614. LibravatarService.SetSecureFallbackHost(parts[2])
  615. } else {
  616. LibravatarService.SetUseHTTPS(false)
  617. LibravatarService.SetFallbackHost(parts[2])
  618. }
  619. }
  620. }
  621. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  622. log.Fatal(4, "Fail to map UI settings: %v", err)
  623. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  624. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  625. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  626. log.Fatal(4, "Fail to map Cron settings: %v", err)
  627. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  628. log.Fatal(4, "Fail to map Git settings: %v", err)
  629. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  630. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  631. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  632. log.Fatal(4, "Fail to map API settings: %v", err)
  633. }
  634. if Mirror.DefaultInterval <= 0 {
  635. Mirror.DefaultInterval = 24
  636. }
  637. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  638. if len(Langs) == 0 {
  639. Langs = defaultLangs
  640. }
  641. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  642. if len(Names) == 0 {
  643. Names = defaultLangNames
  644. }
  645. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  646. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  647. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  648. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  649. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  650. }
  651. // Service settings
  652. var Service struct {
  653. ActiveCodeLives int
  654. ResetPwdCodeLives int
  655. RegisterEmailConfirm bool
  656. DisableRegistration bool
  657. ShowRegistrationButton bool
  658. RequireSignInView bool
  659. EnableNotifyMail bool
  660. EnableReverseProxyAuth bool
  661. EnableReverseProxyAutoRegister bool
  662. EnableCaptcha bool
  663. }
  664. func newService() {
  665. sec := Cfg.Section("service")
  666. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  667. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  668. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  669. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  670. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  671. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  672. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  673. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  674. }
  675. var logLevels = map[string]string{
  676. "Trace": "0",
  677. "Debug": "1",
  678. "Info": "2",
  679. "Warn": "3",
  680. "Error": "4",
  681. "Critical": "5",
  682. }
  683. func newLogService() {
  684. log.Info("Gitea v%s", AppVer)
  685. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  686. LogConfigs = make([]string, len(LogModes))
  687. for i, mode := range LogModes {
  688. mode = strings.TrimSpace(mode)
  689. sec, err := Cfg.GetSection("log." + mode)
  690. if err != nil {
  691. sec, _ = Cfg.NewSection("log." + mode)
  692. }
  693. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  694. // Log level.
  695. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  696. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  697. validLevels)
  698. level, ok := logLevels[levelName]
  699. if !ok {
  700. log.Fatal(4, "Unknown log level: %s", levelName)
  701. }
  702. // Generate log configuration.
  703. switch mode {
  704. case "console":
  705. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  706. case "file":
  707. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  708. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  709. panic(err.Error())
  710. }
  711. LogConfigs[i] = fmt.Sprintf(
  712. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  713. logPath,
  714. sec.Key("LOG_ROTATE").MustBool(true),
  715. sec.Key("MAX_LINES").MustInt(1000000),
  716. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  717. sec.Key("DAILY_ROTATE").MustBool(true),
  718. sec.Key("MAX_DAYS").MustInt(7))
  719. case "conn":
  720. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  721. sec.Key("RECONNECT_ON_MSG").MustBool(),
  722. sec.Key("RECONNECT").MustBool(),
  723. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  724. sec.Key("ADDR").MustString(":7020"))
  725. case "smtp":
  726. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  727. sec.Key("USER").MustString("example@example.com"),
  728. sec.Key("PASSWD").MustString("******"),
  729. sec.Key("HOST").MustString("127.0.0.1:25"),
  730. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  731. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  732. case "database":
  733. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  734. sec.Key("DRIVER").String(),
  735. sec.Key("CONN").String())
  736. }
  737. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  738. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  739. }
  740. }
  741. func newCacheService() {
  742. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  743. switch CacheAdapter {
  744. case "memory":
  745. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  746. case "redis", "memcache":
  747. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  748. default:
  749. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  750. }
  751. log.Info("Cache Service Enabled")
  752. }
  753. func newSessionService() {
  754. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  755. []string{"memory", "file", "redis", "mysql"})
  756. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  757. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  758. SessionConfig.CookiePath = AppSubURL
  759. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  760. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  761. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  762. log.Info("Session Service Enabled")
  763. }
  764. // Mailer represents mail service.
  765. type Mailer struct {
  766. QueueLength int
  767. Name string
  768. Host string
  769. From string
  770. FromEmail string
  771. User, Passwd string
  772. DisableHelo bool
  773. HeloHostname string
  774. SkipVerify bool
  775. UseCertificate bool
  776. CertFile, KeyFile string
  777. EnableHTMLAlternative bool
  778. }
  779. var (
  780. // MailService the global mailer
  781. MailService *Mailer
  782. )
  783. func newMailService() {
  784. sec := Cfg.Section("mailer")
  785. // Check mailer setting.
  786. if !sec.Key("ENABLED").MustBool() {
  787. return
  788. }
  789. MailService = &Mailer{
  790. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  791. Name: sec.Key("NAME").MustString(AppName),
  792. Host: sec.Key("HOST").String(),
  793. User: sec.Key("USER").String(),
  794. Passwd: sec.Key("PASSWD").String(),
  795. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  796. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  797. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  798. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  799. CertFile: sec.Key("CERT_FILE").String(),
  800. KeyFile: sec.Key("KEY_FILE").String(),
  801. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  802. }
  803. MailService.From = sec.Key("FROM").MustString(MailService.User)
  804. parsed, err := mail.ParseAddress(MailService.From)
  805. if err != nil {
  806. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  807. }
  808. MailService.FromEmail = parsed.Address
  809. log.Info("Mail Service Enabled")
  810. }
  811. func newRegisterMailService() {
  812. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  813. return
  814. } else if MailService == nil {
  815. log.Warn("Register Mail Service: Mail Service is not enabled")
  816. return
  817. }
  818. Service.RegisterEmailConfirm = true
  819. log.Info("Register Mail Service Enabled")
  820. }
  821. func newNotifyMailService() {
  822. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  823. return
  824. } else if MailService == nil {
  825. log.Warn("Notify Mail Service: Mail Service is not enabled")
  826. return
  827. }
  828. Service.EnableNotifyMail = true
  829. log.Info("Notify Mail Service Enabled")
  830. }
  831. func newWebhookService() {
  832. sec := Cfg.Section("webhook")
  833. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  834. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  835. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  836. Webhook.Types = []string{"gogs", "slack"}
  837. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  838. }
  839. // NewServices initializes the services
  840. func NewServices() {
  841. newService()
  842. newLogService()
  843. newCacheService()
  844. newSessionService()
  845. newMailService()
  846. newRegisterMailService()
  847. newNotifyMailService()
  848. newWebhookService()
  849. }