setting.go 13 KB

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