setting.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/Unknwon/goconfig"
  14. "github.com/macaron-contrib/session"
  15. "github.com/gogits/gogs/modules/log"
  16. // "github.com/gogits/gogs-ng/modules/ssh"
  17. )
  18. type Scheme string
  19. const (
  20. HTTP Scheme = "http"
  21. HTTPS Scheme = "https"
  22. )
  23. var (
  24. // App settings.
  25. AppVer string
  26. AppName string
  27. AppLogo string
  28. AppUrl string
  29. // Server settings.
  30. Protocol Scheme
  31. Domain string
  32. HttpAddr, HttpPort string
  33. SshPort int
  34. OfflineMode bool
  35. DisableRouterLog bool
  36. CertFile, KeyFile string
  37. StaticRootPath string
  38. EnableGzip bool
  39. // Security settings.
  40. InstallLock bool
  41. SecretKey string
  42. LogInRememberDays int
  43. CookieUserName string
  44. CookieRememberName string
  45. ReverseProxyAuthUser string
  46. // Webhook settings.
  47. WebhookTaskInterval int
  48. WebhookDeliverTimeout int
  49. // Repository settings.
  50. RepoRootPath string
  51. ScriptType string
  52. // Picture settings.
  53. PictureService string
  54. DisableGravatar bool
  55. // Log settings.
  56. LogRootPath string
  57. LogModes []string
  58. LogConfigs []string
  59. // Attachment settings.
  60. AttachmentPath string
  61. AttachmentAllowedTypes string
  62. AttachmentMaxSize int64
  63. AttachmentMaxFiles int
  64. AttachmentEnabled bool
  65. // Cache settings.
  66. CacheAdapter string
  67. CacheInternal int
  68. CacheConn string
  69. EnableRedis bool
  70. EnableMemcache bool
  71. // Session settings.
  72. SessionProvider string
  73. SessionConfig *session.Config
  74. // Global setting objects.
  75. Cfg *goconfig.ConfigFile
  76. ConfRootPath string
  77. CustomPath string // Custom directory path.
  78. ProdMode bool
  79. RunUser string
  80. // I18n settings.
  81. Langs, Names []string
  82. )
  83. func init() {
  84. log.NewLogger(0, "console", `{"level": 0}`)
  85. }
  86. func ExecPath() (string, error) {
  87. file, err := exec.LookPath(os.Args[0])
  88. if err != nil {
  89. return "", err
  90. }
  91. p, err := filepath.Abs(file)
  92. if err != nil {
  93. return "", err
  94. }
  95. return p, nil
  96. }
  97. // WorkDir returns absolute path of work directory.
  98. func WorkDir() (string, error) {
  99. execPath, err := ExecPath()
  100. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  101. }
  102. // NewConfigContext initializes configuration context.
  103. // NOTE: do not print any log except error.
  104. func NewConfigContext() {
  105. workDir, err := WorkDir()
  106. if err != nil {
  107. log.Fatal(4, "Fail to get work directory: %v", err)
  108. }
  109. ConfRootPath = path.Join(workDir, "conf")
  110. Cfg, err = goconfig.LoadConfigFile(path.Join(workDir, "conf/app.ini"))
  111. if err != nil {
  112. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  113. }
  114. CustomPath = os.Getenv("GOGS_CUSTOM")
  115. if len(CustomPath) == 0 {
  116. CustomPath = path.Join(workDir, "custom")
  117. }
  118. cfgPath := path.Join(CustomPath, "conf/app.ini")
  119. if com.IsFile(cfgPath) {
  120. if err = Cfg.AppendFiles(cfgPath); err != nil {
  121. log.Fatal(4, "Fail to load custom 'conf/app.ini': %v", err)
  122. }
  123. } else {
  124. log.Warn("No custom 'conf/app.ini' found, please go to '/install'")
  125. }
  126. AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
  127. AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
  128. AppUrl = Cfg.MustValue("server", "ROOT_URL", "http://localhost:3000")
  129. Protocol = HTTP
  130. if Cfg.MustValue("server", "PROTOCOL") == "https" {
  131. Protocol = HTTPS
  132. CertFile = Cfg.MustValue("server", "CERT_FILE")
  133. KeyFile = Cfg.MustValue("server", "KEY_FILE")
  134. }
  135. Domain = Cfg.MustValue("server", "DOMAIN", "localhost")
  136. HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0")
  137. HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000")
  138. SshPort = Cfg.MustInt("server", "SSH_PORT", 22)
  139. OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE")
  140. DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG")
  141. StaticRootPath = Cfg.MustValue("server", "STATIC_ROOT_PATH", workDir)
  142. LogRootPath = Cfg.MustValue("log", "ROOT_PATH", path.Join(workDir, "log"))
  143. EnableGzip = Cfg.MustBool("server", "ENABLE_GZIP")
  144. InstallLock = Cfg.MustBool("security", "INSTALL_LOCK")
  145. SecretKey = Cfg.MustValue("security", "SECRET_KEY")
  146. LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
  147. CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
  148. CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
  149. ReverseProxyAuthUser = Cfg.MustValue("security", "REVERSE_PROXY_AUTHENTICATION_USER", "X-WEBAUTH-USER")
  150. AttachmentPath = Cfg.MustValue("attachment", "PATH", "data/attachments")
  151. AttachmentAllowedTypes = Cfg.MustValue("attachment", "ALLOWED_TYPES", "image/jpeg|image/png")
  152. AttachmentMaxSize = Cfg.MustInt64("attachment", "MAX_SIZE", 32)
  153. AttachmentMaxFiles = Cfg.MustInt("attachment", "MAX_FILES", 10)
  154. AttachmentEnabled = Cfg.MustBool("attachment", "ENABLE", true)
  155. if err = os.MkdirAll(AttachmentPath, os.ModePerm); err != nil {
  156. log.Fatal(4, "Could not create directory %s: %s", AttachmentPath, err)
  157. }
  158. RunUser = Cfg.MustValue("", "RUN_USER")
  159. curUser := os.Getenv("USER")
  160. if len(curUser) == 0 {
  161. curUser = os.Getenv("USERNAME")
  162. }
  163. // Does not check run user when the install lock is off.
  164. if InstallLock && RunUser != curUser {
  165. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  166. }
  167. // Determine and create root git reposiroty path.
  168. homeDir, err := com.HomeDir()
  169. if err != nil {
  170. log.Fatal(4, "Fail to get home directory: %v", err)
  171. }
  172. RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
  173. if !filepath.IsAbs(RepoRootPath) {
  174. RepoRootPath = filepath.Join(workDir, RepoRootPath)
  175. } else {
  176. RepoRootPath = filepath.Clean(RepoRootPath)
  177. }
  178. if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  179. log.Fatal(4, "Fail to create repository root path(%s): %v", RepoRootPath, err)
  180. }
  181. ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
  182. PictureService = Cfg.MustValueRange("picture", "SERVICE", "server",
  183. []string{"server"})
  184. DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR")
  185. Langs = Cfg.MustValueArray("i18n", "LANGS", ",")
  186. Names = Cfg.MustValueArray("i18n", "NAMES", ",")
  187. }
  188. var Service struct {
  189. RegisterEmailConfirm bool
  190. DisableRegistration bool
  191. RequireSignInView bool
  192. EnableCacheAvatar bool
  193. EnableNotifyMail bool
  194. EnableReverseProxyAuth bool
  195. LdapAuth bool
  196. ActiveCodeLives int
  197. ResetPwdCodeLives int
  198. }
  199. func newService() {
  200. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  201. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  202. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION")
  203. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
  204. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
  205. Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
  206. }
  207. var logLevels = map[string]string{
  208. "Trace": "0",
  209. "Debug": "1",
  210. "Info": "2",
  211. "Warn": "3",
  212. "Error": "4",
  213. "Critical": "5",
  214. }
  215. func newLogService() {
  216. log.Info("%s %s", AppName, AppVer)
  217. // Get and check log mode.
  218. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  219. LogConfigs = make([]string, len(LogModes))
  220. for i, mode := range LogModes {
  221. mode = strings.TrimSpace(mode)
  222. modeSec := "log." + mode
  223. if _, err := Cfg.GetSection(modeSec); err != nil {
  224. log.Fatal(4, "Unknown log mode: %s", mode)
  225. }
  226. // Log level.
  227. levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
  228. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  229. level, ok := logLevels[levelName]
  230. if !ok {
  231. log.Fatal(4, "Unknown log level: %s", levelName)
  232. }
  233. // Generate log configuration.
  234. switch mode {
  235. case "console":
  236. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  237. case "file":
  238. logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
  239. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  240. LogConfigs[i] = fmt.Sprintf(
  241. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  242. logPath,
  243. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  244. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  245. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  246. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  247. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  248. case "conn":
  249. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  250. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
  251. Cfg.MustBool(modeSec, "RECONNECT"),
  252. Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
  253. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  254. case "smtp":
  255. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  256. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  257. Cfg.MustValue(modeSec, "PASSWD", "******"),
  258. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  259. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  260. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  261. case "database":
  262. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  263. Cfg.MustValue(modeSec, "DRIVER"),
  264. Cfg.MustValue(modeSec, "CONN"))
  265. }
  266. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  267. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  268. }
  269. }
  270. func newCacheService() {
  271. CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
  272. if EnableRedis {
  273. log.Info("Redis Enabled")
  274. }
  275. if EnableMemcache {
  276. log.Info("Memcache Enabled")
  277. }
  278. switch CacheAdapter {
  279. case "memory":
  280. CacheInternal = Cfg.MustInt("cache", "INTERVAL", 60)
  281. case "redis", "memcache":
  282. CacheConn = strings.Trim(Cfg.MustValue("cache", "HOST"), "\" ")
  283. default:
  284. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  285. }
  286. log.Info("Cache Service Enabled")
  287. }
  288. func newSessionService() {
  289. SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
  290. []string{"memory", "file", "redis", "mysql"})
  291. SessionConfig = new(session.Config)
  292. SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ")
  293. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  294. SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE")
  295. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  296. SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  297. SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  298. SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
  299. "sha1", []string{"sha1", "sha256", "md5"})
  300. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  301. if SessionProvider == "file" {
  302. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  303. }
  304. log.Info("Session Service Enabled")
  305. }
  306. // Mailer represents mail service.
  307. type Mailer struct {
  308. Name string
  309. Host string
  310. From string
  311. User, Passwd string
  312. }
  313. type OauthInfo struct {
  314. ClientId, ClientSecret string
  315. Scopes string
  316. AuthUrl, TokenUrl string
  317. }
  318. // Oauther represents oauth service.
  319. type Oauther struct {
  320. GitHub, Google, Tencent,
  321. Twitter, Weibo bool
  322. OauthInfos map[string]*OauthInfo
  323. }
  324. var (
  325. MailService *Mailer
  326. OauthService *Oauther
  327. )
  328. func newMailService() {
  329. // Check mailer setting.
  330. if !Cfg.MustBool("mailer", "ENABLED") {
  331. return
  332. }
  333. MailService = &Mailer{
  334. Name: Cfg.MustValue("mailer", "NAME", AppName),
  335. Host: Cfg.MustValue("mailer", "HOST"),
  336. User: Cfg.MustValue("mailer", "USER"),
  337. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  338. }
  339. MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User)
  340. log.Info("Mail Service Enabled")
  341. }
  342. func newRegisterMailService() {
  343. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  344. return
  345. } else if MailService == nil {
  346. log.Warn("Register Mail Service: Mail Service is not enabled")
  347. return
  348. }
  349. Service.RegisterEmailConfirm = true
  350. log.Info("Register Mail Service Enabled")
  351. }
  352. func newNotifyMailService() {
  353. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  354. return
  355. } else if MailService == nil {
  356. log.Warn("Notify Mail Service: Mail Service is not enabled")
  357. return
  358. }
  359. Service.EnableNotifyMail = true
  360. log.Info("Notify Mail Service Enabled")
  361. }
  362. func newWebhookService() {
  363. WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1)
  364. WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5)
  365. }
  366. func NewServices() {
  367. newService()
  368. newLogService()
  369. newCacheService()
  370. newSessionService()
  371. newMailService()
  372. newRegisterMailService()
  373. newNotifyMailService()
  374. newWebhookService()
  375. // ssh.Listen("2022")
  376. }