proxy.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package config
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "github.com/fatedier/frp/models/consts"
  21. "github.com/fatedier/frp/models/msg"
  22. "github.com/fatedier/frp/utils/util"
  23. ini "github.com/vaughan0/go-ini"
  24. )
  25. var (
  26. proxyConfTypeMap map[string]reflect.Type
  27. )
  28. func init() {
  29. proxyConfTypeMap = make(map[string]reflect.Type)
  30. proxyConfTypeMap[consts.TcpProxy] = reflect.TypeOf(TcpProxyConf{})
  31. proxyConfTypeMap[consts.UdpProxy] = reflect.TypeOf(UdpProxyConf{})
  32. proxyConfTypeMap[consts.HttpProxy] = reflect.TypeOf(HttpProxyConf{})
  33. proxyConfTypeMap[consts.HttpsProxy] = reflect.TypeOf(HttpsProxyConf{})
  34. proxyConfTypeMap[consts.StcpProxy] = reflect.TypeOf(StcpProxyConf{})
  35. proxyConfTypeMap[consts.XtcpProxy] = reflect.TypeOf(XtcpProxyConf{})
  36. }
  37. // NewConfByType creates a empty ProxyConf object by proxyType.
  38. // If proxyType isn't exist, return nil.
  39. func NewConfByType(proxyType string) ProxyConf {
  40. v, ok := proxyConfTypeMap[proxyType]
  41. if !ok {
  42. return nil
  43. }
  44. cfg := reflect.New(v).Interface().(ProxyConf)
  45. return cfg
  46. }
  47. type ProxyConf interface {
  48. GetBaseInfo() *BaseProxyConf
  49. UnmarshalFromMsg(pMsg *msg.NewProxy)
  50. UnmarshalFromIni(prefix string, name string, conf ini.Section) error
  51. MarshalToMsg(pMsg *msg.NewProxy)
  52. CheckForCli() error
  53. CheckForSvr(serverCfg ServerCommonConf) error
  54. Compare(conf ProxyConf) bool
  55. }
  56. func NewProxyConfFromMsg(pMsg *msg.NewProxy, serverCfg ServerCommonConf) (cfg ProxyConf, err error) {
  57. if pMsg.ProxyType == "" {
  58. pMsg.ProxyType = consts.TcpProxy
  59. }
  60. cfg = NewConfByType(pMsg.ProxyType)
  61. if cfg == nil {
  62. err = fmt.Errorf("proxy [%s] type [%s] error", pMsg.ProxyName, pMsg.ProxyType)
  63. return
  64. }
  65. cfg.UnmarshalFromMsg(pMsg)
  66. err = cfg.CheckForSvr(serverCfg)
  67. return
  68. }
  69. func NewProxyConfFromIni(prefix string, name string, section ini.Section) (cfg ProxyConf, err error) {
  70. proxyType := section["type"]
  71. if proxyType == "" {
  72. proxyType = consts.TcpProxy
  73. section["type"] = consts.TcpProxy
  74. }
  75. cfg = NewConfByType(proxyType)
  76. if cfg == nil {
  77. err = fmt.Errorf("proxy [%s] type [%s] error", name, proxyType)
  78. return
  79. }
  80. if err = cfg.UnmarshalFromIni(prefix, name, section); err != nil {
  81. return
  82. }
  83. if err = cfg.CheckForCli(); err != nil {
  84. return
  85. }
  86. return
  87. }
  88. // BaseProxyConf provides configuration info that is common to all proxy types.
  89. type BaseProxyConf struct {
  90. // ProxyName is the name of this proxy.
  91. ProxyName string `json:"proxy_name"`
  92. // ProxyType specifies the type of this proxy. Valid values include "tcp",
  93. // "udp", "http", "https", "stcp", and "xtcp". By default, this value is
  94. // "tcp".
  95. ProxyType string `json:"proxy_type"`
  96. // UseEncryption controls whether or not communication with the server will
  97. // be encrypted. Encryption is done using the tokens supplied in the server
  98. // and client configuration. By default, this value is false.
  99. UseEncryption bool `json:"use_encryption"`
  100. // UseCompression controls whether or not communication with the server
  101. // will be compressed. By default, this value is false.
  102. UseCompression bool `json:"use_compression"`
  103. // Group specifies which group the proxy is a part of. The server will use
  104. // this information to load balance proxies in the same group. If the value
  105. // is "", this proxy will not be in a group. By default, this value is "".
  106. Group string `json:"group"`
  107. // GroupKey specifies a group key, which should be the same among proxies
  108. // of the same group. By default, this value is "".
  109. GroupKey string `json:"group_key"`
  110. // ProxyProtocolVersion specifies which protocol version to use. Valid
  111. // values include "v1", "v2", and "". If the value is "", a protocol
  112. // version will be automatically selected. By default, this value is "".
  113. ProxyProtocolVersion string `json:"proxy_protocol_version"`
  114. // BandwidthLimit limit the proxy bandwidth
  115. // 0 means no limit
  116. BandwidthLimit BandwidthQuantity `json:"bandwidth_limit"`
  117. // meta info for each proxy
  118. Metas map[string]string `json:"metas"`
  119. LocalSvrConf
  120. HealthCheckConf
  121. }
  122. func (cfg *BaseProxyConf) GetBaseInfo() *BaseProxyConf {
  123. return cfg
  124. }
  125. func (cfg *BaseProxyConf) compare(cmp *BaseProxyConf) bool {
  126. if cfg.ProxyName != cmp.ProxyName ||
  127. cfg.ProxyType != cmp.ProxyType ||
  128. cfg.UseEncryption != cmp.UseEncryption ||
  129. cfg.UseCompression != cmp.UseCompression ||
  130. cfg.Group != cmp.Group ||
  131. cfg.GroupKey != cmp.GroupKey ||
  132. cfg.ProxyProtocolVersion != cmp.ProxyProtocolVersion ||
  133. cfg.BandwidthLimit.Equal(&cmp.BandwidthLimit) ||
  134. !reflect.DeepEqual(cfg.Metas, cmp.Metas) {
  135. return false
  136. }
  137. if !cfg.LocalSvrConf.compare(&cmp.LocalSvrConf) {
  138. return false
  139. }
  140. if !cfg.HealthCheckConf.compare(&cmp.HealthCheckConf) {
  141. return false
  142. }
  143. return true
  144. }
  145. func (cfg *BaseProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  146. cfg.ProxyName = pMsg.ProxyName
  147. cfg.ProxyType = pMsg.ProxyType
  148. cfg.UseEncryption = pMsg.UseEncryption
  149. cfg.UseCompression = pMsg.UseCompression
  150. cfg.Group = pMsg.Group
  151. cfg.GroupKey = pMsg.GroupKey
  152. cfg.Metas = pMsg.Metas
  153. }
  154. func (cfg *BaseProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) error {
  155. var (
  156. tmpStr string
  157. ok bool
  158. err error
  159. )
  160. cfg.ProxyName = prefix + name
  161. cfg.ProxyType = section["type"]
  162. tmpStr, ok = section["use_encryption"]
  163. if ok && tmpStr == "true" {
  164. cfg.UseEncryption = true
  165. }
  166. tmpStr, ok = section["use_compression"]
  167. if ok && tmpStr == "true" {
  168. cfg.UseCompression = true
  169. }
  170. cfg.Group = section["group"]
  171. cfg.GroupKey = section["group_key"]
  172. cfg.ProxyProtocolVersion = section["proxy_protocol_version"]
  173. if cfg.BandwidthLimit, err = NewBandwidthQuantity(section["bandwidth_limit"]); err != nil {
  174. return err
  175. }
  176. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  177. return err
  178. }
  179. if err = cfg.HealthCheckConf.UnmarshalFromIni(prefix, name, section); err != nil {
  180. return err
  181. }
  182. if cfg.HealthCheckType == "tcp" && cfg.Plugin == "" {
  183. cfg.HealthCheckAddr = cfg.LocalIp + fmt.Sprintf(":%d", cfg.LocalPort)
  184. }
  185. if cfg.HealthCheckType == "http" && cfg.Plugin == "" && cfg.HealthCheckUrl != "" {
  186. s := fmt.Sprintf("http://%s:%d", cfg.LocalIp, cfg.LocalPort)
  187. if !strings.HasPrefix(cfg.HealthCheckUrl, "/") {
  188. s += "/"
  189. }
  190. cfg.HealthCheckUrl = s + cfg.HealthCheckUrl
  191. }
  192. for k, v := range section {
  193. if strings.HasPrefix(k, "meta_") {
  194. cfg.Metas[strings.TrimPrefix(k, "meta_")] = v
  195. }
  196. }
  197. return nil
  198. }
  199. func (cfg *BaseProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  200. pMsg.ProxyName = cfg.ProxyName
  201. pMsg.ProxyType = cfg.ProxyType
  202. pMsg.UseEncryption = cfg.UseEncryption
  203. pMsg.UseCompression = cfg.UseCompression
  204. pMsg.Group = cfg.Group
  205. pMsg.GroupKey = cfg.GroupKey
  206. pMsg.Metas = cfg.Metas
  207. }
  208. func (cfg *BaseProxyConf) checkForCli() (err error) {
  209. if cfg.ProxyProtocolVersion != "" {
  210. if cfg.ProxyProtocolVersion != "v1" && cfg.ProxyProtocolVersion != "v2" {
  211. return fmt.Errorf("no support proxy protocol version: %s", cfg.ProxyProtocolVersion)
  212. }
  213. }
  214. if err = cfg.LocalSvrConf.checkForCli(); err != nil {
  215. return
  216. }
  217. if err = cfg.HealthCheckConf.checkForCli(); err != nil {
  218. return
  219. }
  220. return nil
  221. }
  222. // Bind info
  223. type BindInfoConf struct {
  224. RemotePort int `json:"remote_port"`
  225. }
  226. func (cfg *BindInfoConf) compare(cmp *BindInfoConf) bool {
  227. if cfg.RemotePort != cmp.RemotePort {
  228. return false
  229. }
  230. return true
  231. }
  232. func (cfg *BindInfoConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  233. cfg.RemotePort = pMsg.RemotePort
  234. }
  235. func (cfg *BindInfoConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  236. var (
  237. tmpStr string
  238. ok bool
  239. v int64
  240. )
  241. if tmpStr, ok = section["remote_port"]; ok {
  242. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  243. return fmt.Errorf("Parse conf error: proxy [%s] remote_port error", name)
  244. } else {
  245. cfg.RemotePort = int(v)
  246. }
  247. } else {
  248. return fmt.Errorf("Parse conf error: proxy [%s] remote_port not found", name)
  249. }
  250. return nil
  251. }
  252. func (cfg *BindInfoConf) MarshalToMsg(pMsg *msg.NewProxy) {
  253. pMsg.RemotePort = cfg.RemotePort
  254. }
  255. // Domain info
  256. type DomainConf struct {
  257. CustomDomains []string `json:"custom_domains"`
  258. SubDomain string `json:"sub_domain"`
  259. }
  260. func (cfg *DomainConf) compare(cmp *DomainConf) bool {
  261. if strings.Join(cfg.CustomDomains, " ") != strings.Join(cmp.CustomDomains, " ") ||
  262. cfg.SubDomain != cmp.SubDomain {
  263. return false
  264. }
  265. return true
  266. }
  267. func (cfg *DomainConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  268. cfg.CustomDomains = pMsg.CustomDomains
  269. cfg.SubDomain = pMsg.SubDomain
  270. }
  271. func (cfg *DomainConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  272. var (
  273. tmpStr string
  274. ok bool
  275. )
  276. if tmpStr, ok = section["custom_domains"]; ok {
  277. cfg.CustomDomains = strings.Split(tmpStr, ",")
  278. for i, domain := range cfg.CustomDomains {
  279. cfg.CustomDomains[i] = strings.ToLower(strings.TrimSpace(domain))
  280. }
  281. }
  282. if tmpStr, ok = section["subdomain"]; ok {
  283. cfg.SubDomain = tmpStr
  284. }
  285. return
  286. }
  287. func (cfg *DomainConf) MarshalToMsg(pMsg *msg.NewProxy) {
  288. pMsg.CustomDomains = cfg.CustomDomains
  289. pMsg.SubDomain = cfg.SubDomain
  290. }
  291. func (cfg *DomainConf) check() (err error) {
  292. if len(cfg.CustomDomains) == 0 && cfg.SubDomain == "" {
  293. err = fmt.Errorf("custom_domains and subdomain should set at least one of them")
  294. return
  295. }
  296. return
  297. }
  298. func (cfg *DomainConf) checkForCli() (err error) {
  299. if err = cfg.check(); err != nil {
  300. return
  301. }
  302. return
  303. }
  304. func (cfg *DomainConf) checkForSvr(serverCfg ServerCommonConf) (err error) {
  305. if err = cfg.check(); err != nil {
  306. return
  307. }
  308. for _, domain := range cfg.CustomDomains {
  309. if serverCfg.SubDomainHost != "" && len(strings.Split(serverCfg.SubDomainHost, ".")) < len(strings.Split(domain, ".")) {
  310. if strings.Contains(domain, serverCfg.SubDomainHost) {
  311. return fmt.Errorf("custom domain [%s] should not belong to subdomain_host [%s]", domain, serverCfg.SubDomainHost)
  312. }
  313. }
  314. }
  315. if cfg.SubDomain != "" {
  316. if serverCfg.SubDomainHost == "" {
  317. return fmt.Errorf("subdomain is not supported because this feature is not enabled in remote frps")
  318. }
  319. if strings.Contains(cfg.SubDomain, ".") || strings.Contains(cfg.SubDomain, "*") {
  320. return fmt.Errorf("'.' and '*' is not supported in subdomain")
  321. }
  322. }
  323. return
  324. }
  325. // LocalSvrConf configures what location the client will proxy to, or what
  326. // plugin will be used.
  327. type LocalSvrConf struct {
  328. // LocalIp specifies the IP address or host name to proxy to.
  329. LocalIp string `json:"local_ip"`
  330. // LocalPort specifies the port to proxy to.
  331. LocalPort int `json:"local_port"`
  332. // Plugin specifies what plugin should be used for proxying. If this value
  333. // is set, the LocalIp and LocalPort values will be ignored. By default,
  334. // this value is "".
  335. Plugin string `json:"plugin"`
  336. // PluginParams specify parameters to be passed to the plugin, if one is
  337. // being used. By default, this value is an empty map.
  338. PluginParams map[string]string `json:"plugin_params"`
  339. }
  340. func (cfg *LocalSvrConf) compare(cmp *LocalSvrConf) bool {
  341. if cfg.LocalIp != cmp.LocalIp ||
  342. cfg.LocalPort != cmp.LocalPort {
  343. return false
  344. }
  345. if cfg.Plugin != cmp.Plugin ||
  346. len(cfg.PluginParams) != len(cmp.PluginParams) {
  347. return false
  348. }
  349. for k, v := range cfg.PluginParams {
  350. value, ok := cmp.PluginParams[k]
  351. if !ok || v != value {
  352. return false
  353. }
  354. }
  355. return true
  356. }
  357. func (cfg *LocalSvrConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  358. cfg.Plugin = section["plugin"]
  359. cfg.PluginParams = make(map[string]string)
  360. if cfg.Plugin != "" {
  361. // get params begin with "plugin_"
  362. for k, v := range section {
  363. if strings.HasPrefix(k, "plugin_") {
  364. cfg.PluginParams[k] = v
  365. }
  366. }
  367. } else {
  368. if cfg.LocalIp = section["local_ip"]; cfg.LocalIp == "" {
  369. cfg.LocalIp = "127.0.0.1"
  370. }
  371. if tmpStr, ok := section["local_port"]; ok {
  372. if cfg.LocalPort, err = strconv.Atoi(tmpStr); err != nil {
  373. return fmt.Errorf("Parse conf error: proxy [%s] local_port error", name)
  374. }
  375. } else {
  376. return fmt.Errorf("Parse conf error: proxy [%s] local_port not found", name)
  377. }
  378. }
  379. return
  380. }
  381. func (cfg *LocalSvrConf) checkForCli() (err error) {
  382. if cfg.Plugin == "" {
  383. if cfg.LocalIp == "" {
  384. err = fmt.Errorf("local ip or plugin is required")
  385. return
  386. }
  387. if cfg.LocalPort <= 0 {
  388. err = fmt.Errorf("error local_port")
  389. return
  390. }
  391. }
  392. return
  393. }
  394. // HealthCheckConf configures health checking. This can be useful for load
  395. // balancing purposes to detect and remove proxies to failing services.
  396. type HealthCheckConf struct {
  397. // HealthCheckType specifies what protocol to use for health checking.
  398. // Valid values include "tcp", "http", and "". If this value is "", health
  399. // checking will not be performed. By default, this value is "".
  400. //
  401. // If the type is "tcp", a connection will be attempted to the target
  402. // server. If a connection cannot be established, the health check fails.
  403. //
  404. // If the type is "http", a GET request will be made to the endpoint
  405. // specified by HealthCheckUrl. If the response is not a 200, the health
  406. // check fails.
  407. HealthCheckType string `json:"health_check_type"` // tcp | http
  408. // HealthCheckTimeoutS specifies the number of seconds to wait for a health
  409. // check attempt to connect. If the timeout is reached, this counts as a
  410. // health check failure. By default, this value is 3.
  411. HealthCheckTimeoutS int `json:"health_check_timeout_s"`
  412. // HealthCheckMaxFailed specifies the number of allowed failures before the
  413. // proxy is stopped. By default, this value is 1.
  414. HealthCheckMaxFailed int `json:"health_check_max_failed"`
  415. // HealthCheckIntervalS specifies the time in seconds between health
  416. // checks. By default, this value is 10.
  417. HealthCheckIntervalS int `json:"health_check_interval_s"`
  418. // HealthCheckUrl specifies the address to send health checks to if the
  419. // health check type is "http".
  420. HealthCheckUrl string `json:"health_check_url"`
  421. // HealthCheckAddr specifies the address to connect to if the health check
  422. // type is "tcp".
  423. HealthCheckAddr string `json:"-"`
  424. }
  425. func (cfg *HealthCheckConf) compare(cmp *HealthCheckConf) bool {
  426. if cfg.HealthCheckType != cmp.HealthCheckType ||
  427. cfg.HealthCheckTimeoutS != cmp.HealthCheckTimeoutS ||
  428. cfg.HealthCheckMaxFailed != cmp.HealthCheckMaxFailed ||
  429. cfg.HealthCheckIntervalS != cmp.HealthCheckIntervalS ||
  430. cfg.HealthCheckUrl != cmp.HealthCheckUrl {
  431. return false
  432. }
  433. return true
  434. }
  435. func (cfg *HealthCheckConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  436. cfg.HealthCheckType = section["health_check_type"]
  437. cfg.HealthCheckUrl = section["health_check_url"]
  438. if tmpStr, ok := section["health_check_timeout_s"]; ok {
  439. if cfg.HealthCheckTimeoutS, err = strconv.Atoi(tmpStr); err != nil {
  440. return fmt.Errorf("Parse conf error: proxy [%s] health_check_timeout_s error", name)
  441. }
  442. }
  443. if tmpStr, ok := section["health_check_max_failed"]; ok {
  444. if cfg.HealthCheckMaxFailed, err = strconv.Atoi(tmpStr); err != nil {
  445. return fmt.Errorf("Parse conf error: proxy [%s] health_check_max_failed error", name)
  446. }
  447. }
  448. if tmpStr, ok := section["health_check_interval_s"]; ok {
  449. if cfg.HealthCheckIntervalS, err = strconv.Atoi(tmpStr); err != nil {
  450. return fmt.Errorf("Parse conf error: proxy [%s] health_check_interval_s error", name)
  451. }
  452. }
  453. return
  454. }
  455. func (cfg *HealthCheckConf) checkForCli() error {
  456. if cfg.HealthCheckType != "" && cfg.HealthCheckType != "tcp" && cfg.HealthCheckType != "http" {
  457. return fmt.Errorf("unsupport health check type")
  458. }
  459. if cfg.HealthCheckType != "" {
  460. if cfg.HealthCheckType == "http" && cfg.HealthCheckUrl == "" {
  461. return fmt.Errorf("health_check_url is required for health check type 'http'")
  462. }
  463. }
  464. return nil
  465. }
  466. // TCP
  467. type TcpProxyConf struct {
  468. BaseProxyConf
  469. BindInfoConf
  470. }
  471. func (cfg *TcpProxyConf) Compare(cmp ProxyConf) bool {
  472. cmpConf, ok := cmp.(*TcpProxyConf)
  473. if !ok {
  474. return false
  475. }
  476. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  477. !cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
  478. return false
  479. }
  480. return true
  481. }
  482. func (cfg *TcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  483. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  484. cfg.BindInfoConf.UnmarshalFromMsg(pMsg)
  485. }
  486. func (cfg *TcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  487. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  488. return
  489. }
  490. if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
  491. return
  492. }
  493. return
  494. }
  495. func (cfg *TcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  496. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  497. cfg.BindInfoConf.MarshalToMsg(pMsg)
  498. }
  499. func (cfg *TcpProxyConf) CheckForCli() (err error) {
  500. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  501. return err
  502. }
  503. return
  504. }
  505. func (cfg *TcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) error { return nil }
  506. // UDP
  507. type UdpProxyConf struct {
  508. BaseProxyConf
  509. BindInfoConf
  510. }
  511. func (cfg *UdpProxyConf) Compare(cmp ProxyConf) bool {
  512. cmpConf, ok := cmp.(*UdpProxyConf)
  513. if !ok {
  514. return false
  515. }
  516. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  517. !cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
  518. return false
  519. }
  520. return true
  521. }
  522. func (cfg *UdpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  523. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  524. cfg.BindInfoConf.UnmarshalFromMsg(pMsg)
  525. }
  526. func (cfg *UdpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  527. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  528. return
  529. }
  530. if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
  531. return
  532. }
  533. return
  534. }
  535. func (cfg *UdpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  536. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  537. cfg.BindInfoConf.MarshalToMsg(pMsg)
  538. }
  539. func (cfg *UdpProxyConf) CheckForCli() (err error) {
  540. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  541. return
  542. }
  543. return
  544. }
  545. func (cfg *UdpProxyConf) CheckForSvr(serverCfg ServerCommonConf) error { return nil }
  546. // HTTP
  547. type HttpProxyConf struct {
  548. BaseProxyConf
  549. DomainConf
  550. Locations []string `json:"locations"`
  551. HttpUser string `json:"http_user"`
  552. HttpPwd string `json:"http_pwd"`
  553. HostHeaderRewrite string `json:"host_header_rewrite"`
  554. Headers map[string]string `json:"headers"`
  555. }
  556. func (cfg *HttpProxyConf) Compare(cmp ProxyConf) bool {
  557. cmpConf, ok := cmp.(*HttpProxyConf)
  558. if !ok {
  559. return false
  560. }
  561. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  562. !cfg.DomainConf.compare(&cmpConf.DomainConf) ||
  563. strings.Join(cfg.Locations, " ") != strings.Join(cmpConf.Locations, " ") ||
  564. cfg.HostHeaderRewrite != cmpConf.HostHeaderRewrite ||
  565. cfg.HttpUser != cmpConf.HttpUser ||
  566. cfg.HttpPwd != cmpConf.HttpPwd ||
  567. len(cfg.Headers) != len(cmpConf.Headers) {
  568. return false
  569. }
  570. for k, v := range cfg.Headers {
  571. if v2, ok := cmpConf.Headers[k]; !ok {
  572. return false
  573. } else {
  574. if v != v2 {
  575. return false
  576. }
  577. }
  578. }
  579. return true
  580. }
  581. func (cfg *HttpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  582. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  583. cfg.DomainConf.UnmarshalFromMsg(pMsg)
  584. cfg.Locations = pMsg.Locations
  585. cfg.HostHeaderRewrite = pMsg.HostHeaderRewrite
  586. cfg.HttpUser = pMsg.HttpUser
  587. cfg.HttpPwd = pMsg.HttpPwd
  588. cfg.Headers = pMsg.Headers
  589. }
  590. func (cfg *HttpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  591. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  592. return
  593. }
  594. if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
  595. return
  596. }
  597. var (
  598. tmpStr string
  599. ok bool
  600. )
  601. if tmpStr, ok = section["locations"]; ok {
  602. cfg.Locations = strings.Split(tmpStr, ",")
  603. } else {
  604. cfg.Locations = []string{""}
  605. }
  606. cfg.HostHeaderRewrite = section["host_header_rewrite"]
  607. cfg.HttpUser = section["http_user"]
  608. cfg.HttpPwd = section["http_pwd"]
  609. cfg.Headers = make(map[string]string)
  610. for k, v := range section {
  611. if strings.HasPrefix(k, "header_") {
  612. cfg.Headers[strings.TrimPrefix(k, "header_")] = v
  613. }
  614. }
  615. return
  616. }
  617. func (cfg *HttpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  618. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  619. cfg.DomainConf.MarshalToMsg(pMsg)
  620. pMsg.Locations = cfg.Locations
  621. pMsg.HostHeaderRewrite = cfg.HostHeaderRewrite
  622. pMsg.HttpUser = cfg.HttpUser
  623. pMsg.HttpPwd = cfg.HttpPwd
  624. pMsg.Headers = cfg.Headers
  625. }
  626. func (cfg *HttpProxyConf) CheckForCli() (err error) {
  627. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  628. return
  629. }
  630. if err = cfg.DomainConf.checkForCli(); err != nil {
  631. return
  632. }
  633. return
  634. }
  635. func (cfg *HttpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  636. if serverCfg.VhostHttpPort == 0 {
  637. return fmt.Errorf("type [http] not support when vhost_http_port is not set")
  638. }
  639. if err = cfg.DomainConf.checkForSvr(serverCfg); err != nil {
  640. err = fmt.Errorf("proxy [%s] domain conf check error: %v", cfg.ProxyName, err)
  641. return
  642. }
  643. return
  644. }
  645. // HTTPS
  646. type HttpsProxyConf struct {
  647. BaseProxyConf
  648. DomainConf
  649. }
  650. func (cfg *HttpsProxyConf) Compare(cmp ProxyConf) bool {
  651. cmpConf, ok := cmp.(*HttpsProxyConf)
  652. if !ok {
  653. return false
  654. }
  655. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  656. !cfg.DomainConf.compare(&cmpConf.DomainConf) {
  657. return false
  658. }
  659. return true
  660. }
  661. func (cfg *HttpsProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  662. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  663. cfg.DomainConf.UnmarshalFromMsg(pMsg)
  664. }
  665. func (cfg *HttpsProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  666. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  667. return
  668. }
  669. if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
  670. return
  671. }
  672. return
  673. }
  674. func (cfg *HttpsProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  675. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  676. cfg.DomainConf.MarshalToMsg(pMsg)
  677. }
  678. func (cfg *HttpsProxyConf) CheckForCli() (err error) {
  679. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  680. return
  681. }
  682. if err = cfg.DomainConf.checkForCli(); err != nil {
  683. return
  684. }
  685. return
  686. }
  687. func (cfg *HttpsProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  688. if serverCfg.VhostHttpsPort == 0 {
  689. return fmt.Errorf("type [https] not support when vhost_https_port is not set")
  690. }
  691. if err = cfg.DomainConf.checkForSvr(serverCfg); err != nil {
  692. err = fmt.Errorf("proxy [%s] domain conf check error: %v", cfg.ProxyName, err)
  693. return
  694. }
  695. return
  696. }
  697. // STCP
  698. type StcpProxyConf struct {
  699. BaseProxyConf
  700. Role string `json:"role"`
  701. Sk string `json:"sk"`
  702. }
  703. func (cfg *StcpProxyConf) Compare(cmp ProxyConf) bool {
  704. cmpConf, ok := cmp.(*StcpProxyConf)
  705. if !ok {
  706. return false
  707. }
  708. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  709. cfg.Role != cmpConf.Role ||
  710. cfg.Sk != cmpConf.Sk {
  711. return false
  712. }
  713. return true
  714. }
  715. // Only for role server.
  716. func (cfg *StcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  717. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  718. cfg.Sk = pMsg.Sk
  719. }
  720. func (cfg *StcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  721. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  722. return
  723. }
  724. cfg.Role = section["role"]
  725. if cfg.Role != "server" {
  726. return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
  727. }
  728. cfg.Sk = section["sk"]
  729. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  730. return
  731. }
  732. return
  733. }
  734. func (cfg *StcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  735. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  736. pMsg.Sk = cfg.Sk
  737. }
  738. func (cfg *StcpProxyConf) CheckForCli() (err error) {
  739. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  740. return
  741. }
  742. if cfg.Role != "server" {
  743. err = fmt.Errorf("role should be 'server'")
  744. return
  745. }
  746. return
  747. }
  748. func (cfg *StcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  749. return
  750. }
  751. // XTCP
  752. type XtcpProxyConf struct {
  753. BaseProxyConf
  754. Role string `json:"role"`
  755. Sk string `json:"sk"`
  756. }
  757. func (cfg *XtcpProxyConf) Compare(cmp ProxyConf) bool {
  758. cmpConf, ok := cmp.(*XtcpProxyConf)
  759. if !ok {
  760. return false
  761. }
  762. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  763. !cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) ||
  764. cfg.Role != cmpConf.Role ||
  765. cfg.Sk != cmpConf.Sk {
  766. return false
  767. }
  768. return true
  769. }
  770. // Only for role server.
  771. func (cfg *XtcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  772. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  773. cfg.Sk = pMsg.Sk
  774. }
  775. func (cfg *XtcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  776. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  777. return
  778. }
  779. cfg.Role = section["role"]
  780. if cfg.Role != "server" {
  781. return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
  782. }
  783. cfg.Sk = section["sk"]
  784. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  785. return
  786. }
  787. return
  788. }
  789. func (cfg *XtcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  790. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  791. pMsg.Sk = cfg.Sk
  792. }
  793. func (cfg *XtcpProxyConf) CheckForCli() (err error) {
  794. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  795. return
  796. }
  797. if cfg.Role != "server" {
  798. err = fmt.Errorf("role should be 'server'")
  799. return
  800. }
  801. return
  802. }
  803. func (cfg *XtcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  804. return
  805. }
  806. func ParseRangeSection(name string, section ini.Section) (sections map[string]ini.Section, err error) {
  807. localPorts, errRet := util.ParseRangeNumbers(section["local_port"])
  808. if errRet != nil {
  809. err = fmt.Errorf("Parse conf error: range section [%s] local_port invalid, %v", name, errRet)
  810. return
  811. }
  812. remotePorts, errRet := util.ParseRangeNumbers(section["remote_port"])
  813. if errRet != nil {
  814. err = fmt.Errorf("Parse conf error: range section [%s] remote_port invalid, %v", name, errRet)
  815. return
  816. }
  817. if len(localPorts) != len(remotePorts) {
  818. err = fmt.Errorf("Parse conf error: range section [%s] local ports number should be same with remote ports number", name)
  819. return
  820. }
  821. if len(localPorts) == 0 {
  822. err = fmt.Errorf("Parse conf error: range section [%s] local_port and remote_port is necessary", name)
  823. return
  824. }
  825. sections = make(map[string]ini.Section)
  826. for i, port := range localPorts {
  827. subName := fmt.Sprintf("%s_%d", name, i)
  828. subSection := copySection(section)
  829. subSection["local_port"] = fmt.Sprintf("%d", port)
  830. subSection["remote_port"] = fmt.Sprintf("%d", remotePorts[i])
  831. sections[subName] = subSection
  832. }
  833. return
  834. }
  835. // if len(startProxy) is 0, start all
  836. // otherwise just start proxies in startProxy map
  837. func LoadAllConfFromIni(prefix string, content string, startProxy map[string]struct{}) (
  838. proxyConfs map[string]ProxyConf, visitorConfs map[string]VisitorConf, err error) {
  839. conf, errRet := ini.Load(strings.NewReader(content))
  840. if errRet != nil {
  841. err = errRet
  842. return
  843. }
  844. if prefix != "" {
  845. prefix += "."
  846. }
  847. startAll := true
  848. if len(startProxy) > 0 {
  849. startAll = false
  850. }
  851. proxyConfs = make(map[string]ProxyConf)
  852. visitorConfs = make(map[string]VisitorConf)
  853. for name, section := range conf {
  854. if name == "common" {
  855. continue
  856. }
  857. _, shouldStart := startProxy[name]
  858. if !startAll && !shouldStart {
  859. continue
  860. }
  861. subSections := make(map[string]ini.Section)
  862. if strings.HasPrefix(name, "range:") {
  863. // range section
  864. rangePrefix := strings.TrimSpace(strings.TrimPrefix(name, "range:"))
  865. subSections, err = ParseRangeSection(rangePrefix, section)
  866. if err != nil {
  867. return
  868. }
  869. } else {
  870. subSections[name] = section
  871. }
  872. for subName, subSection := range subSections {
  873. if subSection["role"] == "" {
  874. subSection["role"] = "server"
  875. }
  876. role := subSection["role"]
  877. if role == "server" {
  878. cfg, errRet := NewProxyConfFromIni(prefix, subName, subSection)
  879. if errRet != nil {
  880. err = errRet
  881. return
  882. }
  883. proxyConfs[prefix+subName] = cfg
  884. } else if role == "visitor" {
  885. cfg, errRet := NewVisitorConfFromIni(prefix, subName, subSection)
  886. if errRet != nil {
  887. err = errRet
  888. return
  889. }
  890. visitorConfs[prefix+subName] = cfg
  891. } else {
  892. err = fmt.Errorf("role should be 'server' or 'visitor'")
  893. return
  894. }
  895. }
  896. }
  897. return
  898. }
  899. func copySection(section ini.Section) (out ini.Section) {
  900. out = make(ini.Section)
  901. for k, v := range section {
  902. out[k] = v
  903. }
  904. return
  905. }