setting.go 14 KB

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