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

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