setting.go 13 KB

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