setting.go 13 KB

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