setting.go 14 KB

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