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.

384 lines
11 KiB

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
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
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
10 years ago
10 years ago
  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 base
  5. import (
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "github.com/Unknwon/com"
  14. "github.com/Unknwon/goconfig"
  15. qlog "github.com/qiniu/log"
  16. "github.com/gogits/cache"
  17. "github.com/gogits/session"
  18. "github.com/gogits/gogs/modules/auth/ldap"
  19. "github.com/gogits/gogs/modules/log"
  20. )
  21. // Mailer represents mail service.
  22. type Mailer struct {
  23. Name string
  24. Host string
  25. User, Passwd string
  26. }
  27. type OauthInfo struct {
  28. ClientId, ClientSecret string
  29. Scopes string
  30. AuthUrl, TokenUrl string
  31. }
  32. // Oauther represents oauth service.
  33. type Oauther struct {
  34. GitHub, Google, Tencent,
  35. Twitter, Weibo bool
  36. OauthInfos map[string]*OauthInfo
  37. }
  38. var (
  39. AppVer string
  40. AppName string
  41. AppLogo string
  42. AppUrl string
  43. SshPort int
  44. OfflineMode bool
  45. DisableRouterLog bool
  46. ProdMode bool
  47. Domain string
  48. SecretKey string
  49. RunUser string
  50. RepoRootPath string
  51. ScriptType string
  52. InstallLock bool
  53. LogInRememberDays int
  54. CookieUserName string
  55. CookieRememberName string
  56. Cfg *goconfig.ConfigFile
  57. MailService *Mailer
  58. OauthService *Oauther
  59. LogModes []string
  60. LogConfigs []string
  61. Cache cache.Cache
  62. CacheAdapter string
  63. CacheConfig string
  64. SessionProvider string
  65. SessionConfig *session.Config
  66. SessionManager *session.Manager
  67. PictureService string
  68. DisableGravatar bool
  69. EnableRedis bool
  70. EnableMemcache bool
  71. )
  72. var Service struct {
  73. RegisterEmailConfirm bool
  74. DisableRegistration bool
  75. RequireSignInView bool
  76. EnableCacheAvatar bool
  77. NotifyMail bool
  78. ActiveCodeLives int
  79. ResetPwdCodeLives int
  80. LdapAuth bool
  81. }
  82. // ExecDir returns absolute path execution(binary) path.
  83. func ExecDir() (string, error) {
  84. file, err := exec.LookPath(os.Args[0])
  85. if err != nil {
  86. return "", err
  87. }
  88. p, err := filepath.Abs(file)
  89. if err != nil {
  90. return "", err
  91. }
  92. return path.Dir(strings.Replace(p, "\\", "/", -1)), nil
  93. }
  94. var logLevels = map[string]string{
  95. "Trace": "0",
  96. "Debug": "1",
  97. "Info": "2",
  98. "Warn": "3",
  99. "Error": "4",
  100. "Critical": "5",
  101. }
  102. func newService() {
  103. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  104. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  105. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION", false)
  106. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW", false)
  107. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR", false)
  108. }
  109. func newLogService() {
  110. log.Info("%s %s", AppName, AppVer)
  111. // Get and check log mode.
  112. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  113. LogConfigs = make([]string, len(LogModes))
  114. for i, mode := range LogModes {
  115. mode = strings.TrimSpace(mode)
  116. modeSec := "log." + mode
  117. if _, err := Cfg.GetSection(modeSec); err != nil {
  118. qlog.Fatalf("Unknown log mode: %s\n", mode)
  119. }
  120. // Log level.
  121. levelName := Cfg.MustValue("log."+mode, "LEVEL", "Trace")
  122. level, ok := logLevels[levelName]
  123. if !ok {
  124. qlog.Fatalf("Unknown log level: %s\n", levelName)
  125. }
  126. // Generate log configuration.
  127. switch mode {
  128. case "console":
  129. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  130. case "file":
  131. logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log")
  132. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  133. LogConfigs[i] = fmt.Sprintf(
  134. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  135. logPath,
  136. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  137. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  138. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  139. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  140. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  141. case "conn":
  142. LogConfigs[i] = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  143. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false),
  144. Cfg.MustBool(modeSec, "RECONNECT", false),
  145. Cfg.MustValue(modeSec, "PROTOCOL", "tcp"),
  146. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  147. case "smtp":
  148. LogConfigs[i] = fmt.Sprintf(`{"level":"%s","username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  149. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  150. Cfg.MustValue(modeSec, "PASSWD", "******"),
  151. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  152. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  153. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  154. case "database":
  155. LogConfigs[i] = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level,
  156. Cfg.MustValue(modeSec, "Driver"),
  157. Cfg.MustValue(modeSec, "CONN"))
  158. }
  159. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  160. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  161. }
  162. }
  163. func newLdapService() {
  164. Service.LdapAuth = Cfg.MustBool("security", "LDAP_AUTH", false)
  165. if !Service.LdapAuth {
  166. return
  167. }
  168. nbsrc := 0
  169. for _, v := range Cfg.GetSectionList() {
  170. if matched, _ := regexp.MatchString("(?i)^LDAPSOURCE.*", v); matched {
  171. ldapname := Cfg.MustValue(v, "name", v)
  172. ldaphost := Cfg.MustValue(v, "host")
  173. ldapport := Cfg.MustInt(v, "port", 389)
  174. ldapbasedn := Cfg.MustValue(v, "basedn", "dc=*,dc=*")
  175. ldapattribute := Cfg.MustValue(v, "attribute", "mail")
  176. ldapfilter := Cfg.MustValue(v, "filter", "(*)")
  177. ldapmsadsaformat := Cfg.MustValue(v, "MSADSAFORMAT", "%s")
  178. ldap.AddSource(ldapname, ldaphost, ldapport, ldapbasedn, ldapattribute, ldapfilter, ldapmsadsaformat)
  179. nbsrc++
  180. log.Debug("%s added as LDAP source", ldapname)
  181. }
  182. }
  183. if nbsrc == 0 {
  184. log.Warn("No valide LDAP found, LDAP Authentication NOT enabled")
  185. Service.LdapAuth = false
  186. return
  187. }
  188. log.Info("LDAP Authentication Enabled")
  189. }
  190. func newCacheService() {
  191. CacheAdapter = Cfg.MustValue("cache", "ADAPTER", "memory")
  192. if EnableRedis {
  193. log.Info("Redis Enabled")
  194. }
  195. if EnableMemcache {
  196. log.Info("Memcache Enabled")
  197. }
  198. switch CacheAdapter {
  199. case "memory":
  200. CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
  201. case "redis", "memcache":
  202. CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
  203. default:
  204. qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter)
  205. }
  206. var err error
  207. Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
  208. if err != nil {
  209. qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n",
  210. CacheAdapter, CacheConfig, err)
  211. }
  212. log.Info("Cache Service Enabled")
  213. }
  214. func newSessionService() {
  215. SessionProvider = Cfg.MustValue("session", "PROVIDER", "memory")
  216. SessionConfig = new(session.Config)
  217. SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
  218. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  219. SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
  220. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  221. SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  222. SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  223. SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1")
  224. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  225. if SessionProvider == "file" {
  226. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  227. }
  228. var err error
  229. SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
  230. if err != nil {
  231. qlog.Fatalf("Init session system failed, provider: %s, %v\n",
  232. SessionProvider, err)
  233. }
  234. log.Info("Session Service Enabled")
  235. }
  236. func newMailService() {
  237. // Check mailer setting.
  238. if !Cfg.MustBool("mailer", "ENABLED") {
  239. return
  240. }
  241. MailService = &Mailer{
  242. Name: Cfg.MustValue("mailer", "NAME", AppName),
  243. Host: Cfg.MustValue("mailer", "HOST"),
  244. User: Cfg.MustValue("mailer", "USER"),
  245. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  246. }
  247. log.Info("Mail Service Enabled")
  248. }
  249. func newRegisterMailService() {
  250. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  251. return
  252. } else if MailService == nil {
  253. log.Warn("Register Mail Service: Mail Service is not enabled")
  254. return
  255. }
  256. Service.RegisterEmailConfirm = true
  257. log.Info("Register Mail Service Enabled")
  258. }
  259. func newNotifyMailService() {
  260. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  261. return
  262. } else if MailService == nil {
  263. log.Warn("Notify Mail Service: Mail Service is not enabled")
  264. return
  265. }
  266. Service.NotifyMail = true
  267. log.Info("Notify Mail Service Enabled")
  268. }
  269. func NewConfigContext() {
  270. workDir, err := ExecDir()
  271. if err != nil {
  272. qlog.Fatalf("Fail to get work directory: %s\n", err)
  273. }
  274. cfgPath := filepath.Join(workDir, "conf/app.ini")
  275. Cfg, err = goconfig.LoadConfigFile(cfgPath)
  276. if err != nil {
  277. qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
  278. }
  279. Cfg.BlockMode = false
  280. cfgPaths := []string{os.Getenv("GOGS_CONFIG"), filepath.Join(workDir, "custom/conf/app.ini")}
  281. for _, cfgPath := range cfgPaths {
  282. if com.IsFile(cfgPath) {
  283. if err = Cfg.AppendFiles(cfgPath); err != nil {
  284. qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
  285. }
  286. }
  287. }
  288. AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
  289. AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
  290. AppUrl = Cfg.MustValue("server", "ROOT_URL")
  291. Domain = Cfg.MustValue("server", "DOMAIN")
  292. SshPort = Cfg.MustInt("server", "SSH_PORT", 22)
  293. OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE", false)
  294. DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG", false)
  295. SecretKey = Cfg.MustValue("security", "SECRET_KEY")
  296. InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false)
  297. RunUser = Cfg.MustValue("", "RUN_USER")
  298. curUser := os.Getenv("USER")
  299. if len(curUser) == 0 {
  300. curUser = os.Getenv("USERNAME")
  301. }
  302. // Does not check run user when the install lock is off.
  303. if InstallLock && RunUser != curUser {
  304. qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
  305. }
  306. LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
  307. CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
  308. CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
  309. PictureService = Cfg.MustValue("picture", "SERVICE")
  310. DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR", false)
  311. // Determine and create root git reposiroty path.
  312. homeDir, err := com.HomeDir()
  313. if err != nil {
  314. qlog.Fatalf("Fail to get home directory): %v\n", err)
  315. }
  316. RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
  317. if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  318. qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
  319. }
  320. ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
  321. }
  322. func NewBaseServices() {
  323. newService()
  324. newLogService()
  325. newLdapService()
  326. newCacheService()
  327. newSessionService()
  328. newMailService()
  329. newRegisterMailService()
  330. newNotifyMailService()
  331. }